简体   繁体   English

返回bool的异步方法

[英]Async method that is returning bool

I have an Async method in C# that is calling SQL function which is returning true or false and method is returning bool variable that is true or false. 我在C#中有一个Async方法,它调用返回true或false的SQL函数,方法返回true或false的bool变量。

This is my method: 这是我的方法:

    public async Task<bool> Canlog(string userName, string pass
    {
        Context context = new Context();
        bool queryResult = false;

        using (context )
        {
            using (context .Database.Connection)
            {
                context .Database.Connection.Open();

                string sqlStatment = .....

                queryResult = authorizationContext.Database
                        .SqlQuery<bool>(sqlStatment)
                        .Single();
            }
        }

        return await queryResult;
    }

when I try this, I am getting error in this line return await queryResult that cannot await bool. 当我尝试这个时,我在这行中得到错误返回等待不能等待bool的queryResult。

Single() returns <T> , not Task<T> . Single()返回<T> ,而不是Task<T> What you want is SingleAsync() : 你想要的是SingleAsync()

    return await authorizationContext.Database
                                     .SqlQuery<bool>(sqlStatement)
                                     .SingleAsync();

Also, you can't have your await outside of your using statements because then your DB context will be disposed before the async operation is compelte. 此外,您不能在using语句之外等待,因为在异步操作强制执行之前,您的数据库上下文将被释放。

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

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