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

后端 未结 8 900
忘掉有多难
忘掉有多难 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条回答
  •  鱼传尺愫
    2020-11-28 01:52

    It does support input/output parameters (including RETURN value) if you use DynamicParameters, but in this case the simpler option is simply:

    var id = connection.QuerySingle( @"
    INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
    SELECT CAST(SCOPE_IDENTITY() as int)", new { Stuff = mystuff});
    

    Note that on more recent versions of SQL Server you can use the OUTPUT clause:

    var id = connection.QuerySingle( @"
    INSERT INTO [MyTable] ([Stuff])
    OUTPUT INSERTED.Id
    VALUES (@Stuff);", new { Stuff = mystuff});
    

提交回复
热议问题