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 NewEntity.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With