EF6-将await关键字与Where()子句一起使用 [英] EF6 - Using the await keyword with the Where() clause
问题描述
我正在使用实体框架6编码MVC 5 Internet应用程序,并且在使用.Where()
子句时是否对使用await
关键字有疑问.
I am coding a MVC 5 internet application with entity framework 6 and have a question in regards to using the await
keyword when using the .Where()
clause.
这是我的有效代码:
public async Task<Account> GetAccount(string userName)
{
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;
}
我想按如下方式检索Account object
时使用await关键字:
I am wanting to use the await keyword when retrieving the Account object
as follows:
Account account = await db.accounts.Where(a => a.userName.Equals(userName)).FirstOrDefault();
使用.Where()
子句时可以使用await
关键字吗?
Can the await
keyword be used when using the .Where()
clause?
谢谢.
推荐答案
await关键字只能用于返回"Task ..."的方法,而.Where
或.FirstOrDefault
都不可用(这是其中的最后一个方法)链,因此将是await关键字适用的链)return Task<IEnumerable<Account>>
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>>
从理论上讲,您可以编写自己的扩展方法,该方法仅将.Where
和.FirstOrDefault
方法包装起来.
In theory you could write you own extension method which simply wraps around the .Where
and .FirstOrDefault
methods.
此外,这个问题并非完全是EF特定的,而是一个纯" C#问题.
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.
您可以将整个方法包装在一个Task中,这样最终代码将类似于:
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;
});
}
这篇关于EF6-将await关键字与Where()子句一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!