I need to Remove and Add entities with the same primary key value in a single request, can anybody suggest me the solution?
Below is my sample code that gives the error: Violation of PRIMARY KEY constraint 'PK_Table'. Cannot insert duplicate key in object 'dbo.Table'.
context.Set<Entity>().Attach(existingEntityObj);
Entry(existingEntityObj).State = EntityState.Deleted;
context.Set<Entity>().Add(newEntityObj);
context.Entry<Entity>(newEntityObj).State = EntityState.Added;
context.SaveChanges();
Assume both the objects (existingEntityObj and newEntityObj) have the same value in the primary key property.
thanks in advance!!
Entity Framework 6 introduced methods to add and remove a collection of entities in one go. The DbSet. AddRange() method attaches a collection of entities to the context with Added state, which will execute the INSERT command in the database for all entities on SaveChanges() .
RemoveRange(IEnumerable<Object>) Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called. RemoveRange(Object[]) Begins tracking the given entity in the Deleted state such that it will be removed from the database when SaveChanges() is called.
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit.
You'll need to do two SaveChanges() calls in order to make this work. The problem here is that, while it appears you are first deleting the record and then adding a new one, the framework is actually doing the insert first.
The reason is because Entity Framework doesn't give you granular control over what orders the operations happen in. So your best bet is going to be to wrap the two in separate TransactionScope's which will let you control the individual transactions that are occurring.
You can read more here: https://blogs.msdn.microsoft.com/alexj/2009/01/11/savechangesfalse/
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