C# 获取存储过程返回的值而不是受影响的行
我有一个存储过程,它执行插入并返回(例如StudentID)插入的最后一行C# 获取存储过程返回的值而不是受影响的行,c#,dapper,C#,Dapper,我有一个存储过程,它执行插入并返回(例如StudentID)插入的最后一行 create procedure insertStudent @... insert into ... values... set @StudentId = scope_identity(); select StudentId from ... where StudentId = @StudentId 在代码中,我有 var sql = ...; using(var connection = new SqlC
create procedure insertStudent
@...
insert into ... values...
set @StudentId = scope_identity();
select StudentId from ... where StudentId = @StudentId
在代码中,我有
var sql = ...;
using(var connection = new SqlConnection(connectionString)
{
var parameters = new DynamicParameters();
parameters.Add ...;
...
int studentId = connection.Execute(sql, parameters, commandType : CommandType.StoredProcedure);
...
}
返回受影响的行数
如何获取存储过程返回的StudentId?使用
Query
,而不是Execute
。Execute用于不返回值的查询
Dapper存储库中的文档展示了如何调用返回结果的存储过程:
var user = cnn.Query<User>("spGetUser", new {Id = 1},
commandType: CommandType.StoredProcedure).SingleOrDefault();
您的代码可以简化为:
int studentId = connection.Query<int>("insertStudent", parameters, commandType : CommandType.StoredProcedure)
.SingleOrDefault();
int studentId=connection.Query(“insertStudent”,参数,commandType:commandType.storedProcess)
.SingleOrDefault();
太棒了。非常感谢你!
int studentId = connection.Query<int>("insertStudent", parameters, commandType : CommandType.StoredProcedure)
.SingleOrDefault();