Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 451
user3736648 Avatar asked Dec 10 '14 12:12

user3736648


People also ask

Where can we use the await keyword?

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.

How do you use await command?

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.

What is the purpose of await keyword?

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.

Should I use async with EF core?

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.


1 Answers

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

like image 86
haim770 Avatar answered Sep 21 '22 23:09

haim770