从 SqlConnection.Execute 存储过程中获取插入的 ID
Get inserted ID back from SqlConnection.Execute stored procedure
我正在像这样将数据插入我的数据库:
using (IDbConnection conn = new SqlConnection(connectionString))
{
conn.Execute(storedProcedure, parameters, commandType: CommandType.StoredProcedure);
}
我已经将 select SCOPE_IDENTITY();
添加到我的存储过程中,所以现在从查询中返回了 id。我怎样才能访问它?
这看起来像 Dapper,是吗?所以:不要使用 Execute
,而是使用 QuerySingle<T>
作为您选择的任何 T
- 大概是 int
或 long
:
var id = conn.QuerySingle<int>(storedProcedure, parameters,
commandType: CommandType.StoredProcedure);
附带说明:您可能会发现在 INSERT
期间 use the OUTPUT
clause 更容易。
使用 ExecuteScalar。
using (IDbConnection conn = new SqlConnection(connectionString))
{
var command = conn.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "MyProcedure";
var id = Convert.ToInt32(command.ExecuteScalar());
}
我正在像这样将数据插入我的数据库:
using (IDbConnection conn = new SqlConnection(connectionString))
{
conn.Execute(storedProcedure, parameters, commandType: CommandType.StoredProcedure);
}
我已经将 select SCOPE_IDENTITY();
添加到我的存储过程中,所以现在从查询中返回了 id。我怎样才能访问它?
这看起来像 Dapper,是吗?所以:不要使用 Execute
,而是使用 QuerySingle<T>
作为您选择的任何 T
- 大概是 int
或 long
:
var id = conn.QuerySingle<int>(storedProcedure, parameters,
commandType: CommandType.StoredProcedure);
附带说明:您可能会发现在 INSERT
期间 use the OUTPUT
clause 更容易。
使用 ExecuteScalar。
using (IDbConnection conn = new SqlConnection(connectionString))
{
var command = conn.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "MyProcedure";
var id = Convert.ToInt32(command.ExecuteScalar());
}