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

后端 未结 4 1080
滥情空心
滥情空心 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:48

    The only way you can change INSERT or UPDATE sql that Entity Framework generates is when you configure your model to use stored procedures.

    You can then modify the sql generated in the Up migration for creating the insert and update procedures to use your MERGE sql rather than INSERT and UPDATE

     CREATE PROCEDURE [dbo].[Blog_Insert]  
      @Name nvarchar(max),  
      @Url nvarchar(max)  
    AS  
    BEGIN 
      -- Your Merge Sql goes here
    
      --And you need to use MERGE OUTPUT to get the primary key 
      --instead of SCOPE_IDENTITY()
      --SELECT SCOPE_IDENTITY() AS BlogId 
    END
    

提交回复
热议问题