How can I use use Entity Framework to do a MERGE when I don't know if the record exists?

后端 未结 4 1091
滥情空心
滥情空心 2020-12-05 04:27

In this SO answer about Entity Framework and MERGE, the example for how to code it is this:

public void SaveOrUpdate(MyEntity entity)
{
  if (entity.Id == 0)         


        
4条回答
  •  天命终不由人
    2020-12-05 04:51

    I use AddOrUpdate in this situation. However, I believe it does query the database first in order to decide to issue an insert or update.

    context.MyEntities.AddOrUpdate(e => e.Id, entity);
    

    Update:

    I ran through my debug log files. First it runs:

    SELECT TOP (2) ... WHERE 1 = [Extent1].[Id]
    

    Then it runs either:

    INSERT [dbo].[TestTable](...) VALUES (...)
    SELECT [Id]
    FROM [dbo].[TestTable]
    WHERE @@ROWCOUNT > 0 AND [Id] = scope_identity()
    

    OR:

    UPDATE [dbo].[TestTable]
    SET ...
    WHERE ([Id] = @2)
    

    Update 2: Here's an interesting extension method the uses MERGE: https://gist.github.com/ondravondra/4001192

提交回复
热议问题