当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - True merge statement in Entity Framework

问题描述:

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.

Thanks.

网友答案:

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) {
  context.Target.DeleteObject(notFound);
}

Unfortunately there's not bulk delete.

网友答案:

Not natively to EF.

There's this (https://gist.github.com/ondravondra/4001192) that creates a sql merge statement. It doesn't include the deletion but it's opensoure and should be easy to add a WHEN NOT MATCHED BY SOURCE THEN DELETE or something.

Disclaimer: I'm not associated with that code at all, and just found it around

Or also, you could just use a stored procedure

分享给朋友:
您可能感兴趣的文章:
随机阅读: