从SqlConnection获取插入的ID。执行存储过程

时间:2020-08-05 13:14:46

标签: c# sql-server .net-core dapper sqlconnection

我正在将数据插入数据库中,如下所示:

>>> import math
>>> lower = upper = 1
>>> for i in range(10**6):
        factor = (2**32 - i) / 2**32
        lower = math.nextafter(lower * factor, -math.inf)
        upper = math.nextafter(upper * factor, math.inf)

>>> lower, upper
(2.739014747179961e-51, 2.739014748048138e-51)
>>> upper - lower
8.681767916298978e-61

我已将using (IDbConnection conn = new SqlConnection(connectionString)) { conn.Execute(storedProcedure, parameters, commandType: CommandType.StoredProcedure); } 添加到存储过程中,因此现在从查询中返回了ID。我该如何访问?

2 个答案:

答案 0 :(得分:0)

这看起来像达珀,是吗?因此:对于选择的Execute(大概是QuerySingle<T>T,请使用int,而不要使用long

var id = conn.QuerySingle<int>(storedProcedure, parameters,
    commandType: CommandType.StoredProcedure);

作为旁注:您可能会发现INSERT期间use the OUTPUT clause更容易。

答案 1 :(得分:0)

使用ExecuteScalar。

using (IDbConnection conn = new SqlConnection(connectionString))
{
   var command = conn.CreateCommand();
   command.CommandType = CommandType.StoredProcedure;
   command.CommandText = "MyProcedure";
   var id = Convert.ToInt32(command.ExecuteScalar());
}