0

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.

1
  • 3
    The method is an asynchronous method - are you sure about that? The method you're calling from has to be async. Show the whole method (or at least the signature). Commented Aug 13, 2014 at 16:08

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I may be mistake, but shouldn't (not always) an ansyc method return task so it can be awaited?
@ErikPhilips We have no idea if this is a top level method or not, so there really isn't any way of knowing what it ought to return.
@Servy I definitely agree. I find that more often than not, it's best to at least return Task as an example in these instances and talk about them then it would be to assume void.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.