开发者

How to Add existing entity as a new Entity with Entity Framework

开发者 https://www.devze.com 2023-01-08 07:58 出处:网络
I want to create a copy my object in my DB with using Entity Framework first I got my \"Book\" from DB

I want to create a copy my object in my DB with 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 as a new object

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

Also I trid to initilize EntityKey of Book it didnt work

Is there any way doing this without creatin开发者_如何转开发g new Book and copy properties from old one?

Thanks


You need to fetch the entity, change the EntityState to Added in the ObjectStateManager and 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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消