我有一个执行检查并返回一行或非零返回值的存储过程:
CREATE PROCEDURE dbo.ConditionalGet
@ID INT
AS
BEGIN
-- this is a silly made up condition just to test the issue
IF @ID % 2 = 1
BEGIN
RETURN -1
END
SELECT *
FROM MyTable
WHERE ID = @ID
RETURN 0
END
我有一个使用 Dapper 返回结果或抛出异常的 C# repo 类:
public class Repo
{
public MyClass Get(int id)
{
using (var conn = GetSqlConnection())
{
var p = new { ID = id };
var pWithReturnValue = new DynamicParameters(p);
p.Add("return", null, DbType.Int32, ParameterDirection.ReturnValue);
var result = conn.Query<MyClass>("dbo.ConditionalGet", p, commandType: CommandType.StoredProcedure);
var errorCode = p.Get<int>("return");
if (errorCode != 0)
throw new RepositoryGetException(errorCode);
return result.FirstOrDefault();
}
}
}
这按预期工作:当 id 可以被 2 整除时,返回水合对象,否则抛出异常。
但是,当我使代码异步时,这失败了!
public class Repo
{
public async Task<MyClass> Get(int id)
{
using (var conn = GetSqlConnection())
{
var p = new { ID = id };
var pWithReturnValue = new DynamicParameters(p);
p.Add("return", null, DbType.Int32, ParameterDirection.ReturnValue);
// this is the only change!
var result = await conn.QueryAsync<MyClass>("dbo.ConditionalGet", p, commandType: CommandType.StoredProcedure);
var errorCode = p.Get<int>("return");
if (errorCode != 0)
throw new RepositoryGetException(errorCode);
return result.FirstOrDefault();
}
}
}
这将引发 InvalidOperationException“未选择任何列”!
我很喜欢这里的模式,想异步使用它,为什么会失败呢?我试过关闭和打开缓冲,但没有任何区别。
最佳答案
目前 Dapper 不支持不执行 SELECT 语句的异步方法。
Github 中有一个 Unresolved 问题:
https://github.com/StackExchange/Dapper/issues/591
你现在要做的是:
ALTER PROCEDURE dbo.ConditionalGet
@ID INT,
@Output INT OUTPUT
AS
BEGIN
-- this is a silly made up condition just to test the issue
IF @ID % 2 = 1
BEGIN
SET @Output = -1
END
ELSE BEGIN
SET @Output = 0
END
SELECT *
FROM MyTable
WHERE ID = @ID
END
关于c# - 为什么 Dapper QueryAsync<T> 的行为与具有存储过程返回值的 Query<T> 不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45965438/