GSeriousB
GSeriousB

Reputation: 33

Cannot await my class

I am creating an ASP.NET Web Form. I created a User class which inherits from IUser<string>. In an other class, ApplicationUserStore which inherits from IUserStore<User>, I have two errors(the same error on both methods).

In the

public async Task<User> FindByNameAsync(string userName) 
    { return await database.Users.Where(x => x.Username == userName).First(); }

and

public async Task<User> FindByIdAsync(string userId) 
    { return await database.Users.Where(x => x.Id == userId).First(); }

methdos I get the error: Cannot await User.

Why? What should I do?

Thanks!

Upvotes: 0

Views: 539

Answers (1)

Kirk Woll
Kirk Woll

Reputation: 77546

First() is not an async-aware method. It just executes the query synchronously. What you want is FirstAsync(), an extension method defined in System.Data.Entity. So add:

using System.Data.Entity;

To your class, and modify your code to look like:

public async Task<User> FindByNameAsync(string userName) 
{ 
    return await database.Users.Where(x => x.Username == userName).FirstAsync(); 
}

This works, because FirstAsync returns a task that is awaitable.

Upvotes: 5

Related Questions