How do I perform an insert and return inserted identity with Dapper?

后端 未结 8 883
忘掉有多难
忘掉有多难 2020-11-28 01:45

How do I perform an insert to database and return inserted identity with Dapper?

I\'ve tried something like this:

string sql = \"DECLARE @ID int; \"          


        
8条回答
  •  萌比男神i
    2020-11-28 01:53

    KB:2019779,"You may receive incorrect values when using SCOPE_IDENTITY() and @@IDENTITY", The OUTPUT clause is the safest mechanism:

    string sql = @"
    DECLARE @InsertedRows AS TABLE (Id int);
    INSERT INTO [MyTable] ([Stuff]) OUTPUT Inserted.Id INTO @InsertedRows
    VALUES (@Stuff);
    SELECT Id FROM @InsertedRows";
    
    var id = connection.Query(sql, new { Stuff = mystuff}).Single();
    

提交回复
热议问题