开发者

Problem saving cloned EF entity to DB

开发者 https://www.devze.com 2023-02-13 08:27 出处:网络
I have managed to successfully clone an EF entity using serialization and deserialization. If I set the EntityKey to nothing, I can add it to the context. But when I try to SaveChanges, I get an error

I have managed to successfully clone an EF entity using serialization and deserialization. If I set the EntityKey to nothing, I can add it to the context. But when I try to SaveChanges, I get an error saying that the primary key must be unique. This makes sense since the clone has the same key. So I need to change it beforehand.

But the primary key is autoassigned by the DB (SQLite) upon insertion, and since the PK is not nullable I cannot set NewEntity.ID=Nothing, which I presume would tell the context that this entity should receive a temporary key until it is inserted.

If I set New开发者_开发百科Entity.ID = 30804328 or some arbitrary (unused) number, it will save to DB fine. But I am very unkeen to query for an unused ID value every time I want to clone an entity.

I understood that the context would treat a detached entity as new when it was 'AddObject'ed, and assign it a temporary key so the DB could do the assignment and then the context would receive the updates. Is this not the case?

How do I resolve this? Thanks for any advice!


This is also covered here: Cloning data on Entity Framework

If looks like the following code is the way to go:

  context.Detach(entity);      
  entityCollection.Add(entity);
  context.SaveChanges(); // New id will be assigned here


I FOUND THE SOLUTION FINALLY. The problem was that the table involved had a primary key identity but Autoincrement was not set. It appears that though the ID key is zero by default when creating a new entity, and it cannot be changed by assignment, it is auto-assigned in the case that Autoincrement is set. But clearly this cannot be resolved automatically if autoincrement (or computed) is not set.

0

精彩评论

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