c# - 如何在异步 Controller 中使用 Dapper?

标签 c# asp.net-mvc asynchronous asp.net-mvc-5

这是我第一次使用 async/await 与 Dapper ORM。我不断收到消息说我的 Controller 缺少等待方法。如何在代码中正确插入await方法?

public async Task<ActionResult> index(int? page)
{

    if (page == null)
    {
        page = 1;
        ViewBag.page = page;
    }
    else
    {

        ViewBag.page = page;
    }
    string Connectionstring = ConfigurationManager.ConnectionStrings["mycontext"].ConnectionString;
    using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
    {

        sqlConnection.Open();
        var sqlM = @"SELECT * from threads order by activities desc";
        var resultM = sqlConnection.Query<thread>(sqlM).ToList();
        await Task.WhenAll(resultM);
        return View(new homepage { panel = resultM });
    }


}

我尝试过 await Task.WhenAll(resultM); 但它没有改变任何东西。

最佳答案

您收到警告是因为您没有在 Controller 中使用任何异步方法。事实上,没有理由将其标记为 async .

为了真正使方法异步,您需要使用 Dapper 的异步方法并等待它们。请参阅Using Async Await keywords with Dapper另一个例子。

在您的代码中,它看起来像:

public async Task<ActionResult> index(int? page)
{

    if (page == null)
    {
        page = 1;
        ViewBag.page = page;
    }
    else
    {

        ViewBag.page = page;
    }

    string Connectionstring = ConfigurationManager.ConnectionStrings["mycontext"].ConnectionString;
    using (System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(Connectionstring))
    {
        await sqlConnection.OpenAsync();

        var sqlM = @"SELECT * from threads order by activities desc";
        var resultM = await sqlConnection.QueryAsync<thread>(sqlM);

        return View(new homepage { panel = resultM });
    }
}

如果resultM必须是List<thread>而不是IEnumerable<T> ,您可以调用ToList - 但请确保它是在等待异步调用之后

关于c# - 如何在异步 Controller 中使用 Dapper?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36462765/

相关文章:

c# - 使用 Json.NET 进行不安全的反序列化

c# - 从单独的线程发送邮件时出错 - asp.net/C#

javascript - "atomic"操作被异步 ajax 回调干扰

c# - 从同步服务层边界调用异步方法

sql-server-2008 - SQL Server 在线程中触发并运行 CLR 方法

c# - 表达式树的重写

c# - C# 中的泛型方法

asp.net-mvc - 使用 Paypal Rest APi 时,远程服务器返回错误 : (401) Unauthorized.

c# - 我可以在一个 Controller 中有两个 View 模型吗?

c# - 身份的双重外键困境