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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With