EF6 - Using the await keyword with the Where() clause

£可爱£侵袭症+ 提交于 2019-12-04 06:47:00

The await keyword can only be used on methods that return "Task...", neither .Where nor .FirstOrDefault (Which is the last method in the chain, and thus would be the one the await keyword would apply to) return Task<IEnumerable<Account>>

In theory you could write you own extension method which simply wraps around the .Where and .FirstOrDefault methods.

Also, this question isn't exactly EF specific, but rather a 'pure' C# question.

public static class ExtensionMethods
{
    public static async Task<IEnumerable<T>> WhereAsync<T>(this IEnumerable<T> source, Func<T, bool> selector)
    {
        return await Task.Run(() => source.Where(selector));
    }
}

Although that would be kind of overkill imho.

You could just wrap your entire method in a Task, so your final code would be something like:

public async Task<Account> GetAccount(string userName)
{
    return await Task.Run(() =>
    {
        if (Session[userName] == null)
        {
            Account account = db.accounts.Where(a => a.userName.Equals(userName)).FirstOrDefault();
            if (account == null)
            {
                //log out
                return null;
            }
            Session[userName] = account;
        }
        return Session[userName] as Account;
    });
}

There is no WhereAsync() method provided by EF (obviously because it can't potentially block, since LINQ uses deferred-execution), but since you're performing a FirstOrDefault() you could simply use the FirstOrDefaultAsync() method:

Account account = await db.accounts.FirstOrDefaultAsync(a => a.userName.Equals(userName));

See MSDN

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!