binks
binks

Reputation: 1033

Why cant I use await?

I'm working with Identity 2.0 in MVC5, and I'm trying to get the first role for the current user.

This bit of code doesn't report any errors:

var DatabaseContext = new ApplicationDbContext();
var thisUserAccount = DatabaseContext.Users.FirstAsync(u => u.Id == Id);

This bit of code:

var DatabaseContext = new ApplicationDbContext();
var thisUserAccount = await DatabaseContext.Users.FirstAsync(u => u.Id == Id);

reports the following error:

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'

The method is an asynchronous method, so why cant I use "await"?

Also, will calling:

DatabaseContext.Users.Load();

before the FirstAsync optimise things a bit (rather than building a ToList which I'm assuming FirstSync does)?

I'm still trying to get to grips with what the async stuff can do, so any useful links will be much appreciated.

Upvotes: 0

Views: 383

Answers (2)

Seymour
Seymour

Reputation: 7067

The following characteristics summarize what makes a method async (your missing the first).

  • The method signature includes an async modifier.
  • Note: The name of an async method, by convention, ends with an "Async" suffix.
  • The return type is one of the following types:
    • Task<TResult> if your method has a return statement in which the operand has type TResult.
    • Task if your method has no return statement or has a return statement with no operand.
    • Void if you're writing an async event handler.

The following link provides a good overview of asynchronous programming using async and await:
http://msdn.microsoft.com/en-us/library/hh191443.aspx

Upvotes: 2

Sean
Sean

Reputation: 62472

You need to mark the method that's using await as being async:

async Task<UserAccount> DoStuff()
{
 var DatabaseContext = new ApplicationDbContext();
 var thisUserAccount = await DatabaseContext.Users.FirstAsync(u => u.Id == Id);

 return thisUserAccount;
}

That's what the error message is telling you.

Upvotes: 5

Related Questions