为什么我不能直接访问属性".SingleAsync().Property"?

Tân*_*Tân 4 .net c# async-await

我的测试代码:

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
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:我不能直接声明pictureUrl这样:

string pictureUrl = await db.UserProfile.SingleAsync(x => x.Id == id).PictureUrl;
Run Code Online (Sandbox Code Playgroud)

我试过这样做,它告诉我错误信息:

'Task<UserProfileViewModels>'不包含定义, 'PictureUrl'也没有'PictureUrl'接受第一个类型参数的扩展方法'Task<UserProfileViewModels>'.

你能解释一下为什么吗?

i3a*_*non 8

SingleAsync返回一个Task<UserProfileViewModels>.那项任务没有你的财产.您需要等待任务以获取实际UserProfileViewModels结果

要告诉编译器你想要结果的属性而不是你需要在括号中包围await表达式的任务:

string pictureUrl = (await db.UserProfile.SingleAsync(x => x.Id == id)).PictureUrl;
Run Code Online (Sandbox Code Playgroud)