Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why cannot I directly access property ".SingleAsync().Property"?

My test code:

using (var db = new MyDbContext())
{
  string id = "";
  string pictureUrl = db.UserProfile.Single(x => x.Id == id).PictureUrl; //valid syntax

  var user = await db.UserProfile.SingleAsync(x => x.Id == id); //valid syntax
  string _pictureUrl = user.PictureUrl; //valid syntax
}

My problem is: I cannot directly declare pictureUrl like this:

string pictureUrl = await db.UserProfile.SingleAsync(x => x.Id == id).PictureUrl;

I've tried to do that, it threw me error message:

'Task<UserProfileViewModels>' does not contain a definition for 'PictureUrl' and no extension method 'PictureUrl' accepting a first argument of type 'Task<UserProfileViewModels>' could be found.

Can you explain me why?

like image 297
Tân Avatar asked Dec 05 '15 08:12

Tân


1 Answers

SingleAsync returns a Task<UserProfileViewModels>. That task doesn't have your property on it. You need to await the task to get back the actual UserProfileViewModels result

To tell the compiler you want the property of the result and not the task you need to surround the await expression in a parenthesis:

string pictureUrl = (await db.UserProfile.SingleAsync(x => x.Id == id)).PictureUrl;
like image 137
i3arnon Avatar answered Nov 15 '22 12:11

i3arnon