我正在尝试 dapper 中的异步支持,在运行一个简单的用例时,我遇到了以下问题。我有一个 ApiController,它只是使用 dapper 触发日志条目以在数据库中创建它。我的数据库连接很好。当我使用 dapper 的查询扩展方法运行同步版本时,一切正常。当我将 QueryAsync 与 async/await 构造一起使用时,我收到 InvalidOperationException。代码如下所示
public class BackgroundController : ApiController
{
[HttpGet]
public async Task<HttpResponseMessage> Run(string op)
{
using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Backgrounder"].ConnectionString))
{
const string sql =
"Insert Into SimpleLog (message, threadid, created) Values(@message, @threadid, @created); " +
"SELECT CAST(SCOPE_IDENTITY() as int)";
var results = await (connection.QueryAsync<int>(sql, new { message = "new log record", threadid = "1", created = DateTime.Now }));
var id = results.SingleOrDefault();
Debug.WriteLine("inserted log record id: " + id);
}
return this.Request.CreateResponse(HttpStatusCode.OK);
}
}
此外,堆栈跟踪如下所示:
位于 System.Data.SqlClient.SqlCommand.b_24(任务 1 result)
at System.Threading.Tasks.ContinuationResultTaskFromResultTask
2.InnerInvoke()
在 System.Threading.Tasks.Task.Execute()
--- 从先前抛出异常的位置开始的堆栈跟踪结束 ---
在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter 1.GetResult()
at Dapper.SqlMapper.<QueryAsync>d__69
1.C:\Dev\Dapper\Dapper NET45\SqlMapperAsync.cs 中的 MoveNext():第 21 行
--- 从先前抛出异常的位置开始的堆栈跟踪结束 ---
在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(任务任务)
在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
在WebApiBackgrounder.Controllers.BackgroundController.d_0.MoveNext()
当 dapper 调用 ExecuteReaderAsync 时,它似乎失败了。有人知道如何解决这个问题吗?
编辑
这是连接字符串
<add name="Backgrounder" providerName="System.Data.SqlClient" connectionString="Data Source=LPW7X6530;Initial Catalog=Sandbox;Integrated Security=SSPI;" />
最佳答案
根据错误消息,听起来连接未打开。碰巧的是,dapper 通常会尝试为您执行此操作 - 因此您没有首先调用 Open() 并不是没有道理的 - 我想我们错过了这一点。现在:在连接上调用 Open()。
关于asp.net-web-api - 在 Dapper 中调用 QueryAsync 会抛出 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18713274/