我的测试代码:
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
}
我的问题是:我不能直接声明 pictureUrl
像这样:
string pictureUrl = await db.UserProfile.SingleAsync(x => x.Id == id).PictureUrl;
我试过这样做,但它向我抛出错误信息:
'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.
你能解释一下为什么吗?
最佳答案
SingleAsync
返回 Task<UserProfileViewModels>
.该任务没有您的属性(property)。您需要等待任务才能取回实际的 UserProfileViewModels
结果
要告诉编译器您需要结果的属性而不是任务,您需要将 await 表达式括在括号中:
string pictureUrl = (await db.UserProfile.SingleAsync(x => x.Id == id)).PictureUrl;
关于c# - 为什么我不能直接访问属性 ".SingleAsync().Property"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34102697/