EF6 - 在 Where() 子句中使用 await 关键字 [英] EF6 - Using the await keyword with the Where() clause
问题描述
我正在使用实体框架 6 编写 MVC 5 互联网应用程序,并且在使用 .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对象
时使用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 关键字适用的方法)返回 Task
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));
}
}
虽然这有点矫枉过正.
您可以将整个方法包装在一个任务中,因此您的最终代码将类似于:
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 - 在 Where() 子句中使用 await 关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!