How to add an existing object as a new Entity Framework object

I want to create a copy of my object in my DB using Entity Framework

first i got my “book” from db

var entity1 = new testEntities();
var book= entity1.Books.First();
entity1.Dispose();

then I tried to add this object to a new object

var entity2 = new testEntities();
book.Id = 0;
entity2.SaveChanges();
entity2.Dispose();

Also i'm trying to initialize EntityKey books it didn't work

Is there a way to do this without creating new Book and copy properties from the old?

thank

+5
source share
1 answer

You need to extract the object, change EntityStateto Addedin ObjectStateManagerand call SaveChanges:

var entity1 = new testEntities();
var book = entity1.Books.First();

ObjectStateEntry bookEntry = entity1.ObjectStateManager.GetObjectStateEntry(book);
bookEntry.ChangeState(EntityState.Added);

entity1.SaveChanges();

This will copy your "book."

+6
source

All Articles