Problem storing cloned EF object in DB

I was able to successfully clone an EF object using serialization and deserialization. If I installed EntityKey nothing, I can add it to the context. But when I try SaveChanges, I get a message that the primary key must be unique. This makes sense because the clone has the same key. Therefore, I need to change it in advance.

But the primary key is automatically assigned to the database (SQLite) upon insertion, and since PK is not NULL, I cannot set NewEntity.ID = Nothing, which, I believe, tells the context that this object should receive a temporary key until he is inserted.

If I set NewEntity.ID = 30804328 or some arbitrary (unused) number, it will save in the database in order. But I really do not want to request an unused ID value every time I want to clone an object.

I realized that the context would consider the individual object as new when it was "AddObject", and assign it a temporary key so that the database can perform the assignment, and then the context receives updates. This is not true?

How do i solve this? Thanks for any advice!

+3
source share
2 answers

. , , . , ID , , Autoincrement. , , ( ) .

+1

: Entity Framework

:

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

Source: https://habr.com/ru/post/1794890/


All Articles