True merge statement in Entity Framework

c# entity-framework-6


Is there a true equivalent of the T-SQL MERGE statement in EF? I know they added AddOrUpdate in a previous version which obviously handles the add or update aspect. It's missing the when not matched from source then delete from the target table.

This particular process is literally just syncing down a third party json structure wholesale. I haven't found anything on a wrapped add / update / delete function in Entity Framework. Thought I would ask on here or for any creative thoughts on wrapping this versus enumerating over the entity, checking for existence, and deleting where the key exists in the DB but not in the source entity.


8/28/2015 7:19:31 PM

Accepted Answer

It's a bit of an odd one but you could select records based on their ID not being contained in the set you have from the 'source' entities, then delete those from the DbContext.

var sourceIds = source.Select(s=>s.Id);
var notFounds = context.Target.Select(s=>!sourceIds.Contains(s.Id));
foreach (var notFound in notFounds) {

Unfortunately there's not bulk delete.

8/28/2015 6:50:49 PM

Popular Answer

After pouring thru a series of 3rd party solutions for this, I finally found one that does a perfect job.

It's blazing fast and required a nuget install, a using, and one line of code.


(I also found bulk update useful.)


The functions take in a list of entities.

My full context is something like:

public void Merge(MyDataBaseEntity[] array)
     using (var ctx = new Entities())
         var list = array.ToList();

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow