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.
Here is my code that works:
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;
}
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();
Can the await
keyword be used when using the .Where()
clause?
Thanks in advance.
The await keyword will ask the execution to wait until the defined task gets executed. It allows the use of await Keyword inside the functions with async keyword. Using await in any other way will cause a syntax error. The use of the async keyword happens at the beginning of the function declaration.
The await operator is used to wait for a Promise. It can be used inside an Async block only. The keyword Await makes JavaScript wait until the promise returns a result. It has to be noted that it only makes the async function block wait and not the whole program execution.
The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any.
Generally speaking, if there are asynchronous APIs, then you should use them for new code. Asynchronous code frees up the calling thread. If your application is a GUI application, this can free up the UI thread; if your application is a server application, this can free up threads to handle other requests.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With