Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: Remove and Add entities with same key in a single request

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!!

like image 494
ANKIT Avatar asked Jul 29 '16 16:07

ANKIT


People also ask

Which method can be used to add a collection of entities in one go?

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() .

What is RemoveRange in Entity Framework?

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.

What is a DbContext?

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.


1 Answers

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/

like image 77
Kyle Goode Avatar answered Oct 05 '22 04:10

Kyle Goode