简体   繁体   English

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

[英]How do I use Dapper in an asynchronous controller?

This is my first time using async/await with the Dapper ORM. 这是我第一次在Dapper ORM中使用async / await。 I keep getting the message that my controller lacks the await method. 我不断收到消息,说我的控制器缺少await方法。 How can I correctly insert the await method in my code? 如何在我的代码中正确插入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 });
    }


}

I have tried await Task.WhenAll(resultM); 我已经尝试await Task.WhenAll(resultM); but it didn't change anything. 但它并没有改变任何东西。

You're getting the warning because you aren't using any asynchronous methods in the controller. 之所以收到警告,是因为您未在控制器中使用任何异步方法。 As it is, there's no reason to mark it as async . 实际上,没有理由将其标记为async

In order to actually make the method asynchronous, you need to use Dapper's async methods and await them. 为了实际使方法异步,您需要使用Dapper的异步方法并等待它们。 See Using Async Await keywords with Dapper for another example of this. 有关此示例的其他信息,请参见将Dashboard和Async Await关键字一起使用

In your code, it would look like: 在您的代码中,它看起来像:

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 });
    }
}

If resultM must be a List<thread> instead of IEnumerable<T> , you can call ToList - but make sure it's after awaiting the asynchronous call. 如果resultM必须是List<thread>而不是IEnumerable<T> ,则可以调用ToList但请确保它等待异步调用之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM