如何在异步控制器中使用Dapper?

时间:2016-04-06 21:33:02

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

这是我第一次使用Dapper ORM进行async / await。我不断得到我的控制器缺少await方法的消息。如何在代码中正确插入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);,但它没有改变任何内容。

1 个答案:

答案 0 :(得分:4)

您收到警告,因为您没有在控制器中使用任何异步方法。实际上,没有理由将其标记为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 - 但请确保 等待异步调用