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

后端 未结 8 905
忘掉有多难
忘掉有多难 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 02:00

    The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).

    You can return it as an int by casting it as follows:

    string sql = @"
    INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
    SELECT CAST(SCOPE_IDENTITY() AS INT)";
    
    int id = connection.Query(sql, new { Stuff = mystuff}).Single();
    

提交回复
热议问题