我将Object引用未设置为对象的实例。错误
这是我的代码:
public ActionResult Profile(string id)
{
News_Application.NewsDatabaseEntities db = new News_Application.NewsDatabaseEntities();
var result = (from u in db.AspNetUsers
where u.Id == id
select new { u.Id, u.WriterName, u.ProfilePicture }).FirstOrDefault();
UserViewModel mo = new UserViewModel();
mo.id = result.Id;
mo.WriterName = result.WriterName;
mo.WriterImage = result.ProfilePicture;
return View(mo);
}
请帮帮我。非常感谢你
答案 0 :(得分:0)
我认为您的LINQ查询为您所拥有的where条件提供了NULL。但是您试图访问result
的属性值而不检查它是否为空
public ActionResult Profile(string id)
{
var db = new News_Application.NewsDatabaseEntities();
var result = (from u in db.AspNetUsers
where u.Id == id
select new { u.Id, u.WriterName, u.ProfilePicture }).FirstOrDefault();
if(result==null)
{
return Content("No records matching the where condition");
//to do : Change to a Not found view.
}
UserViewModel mo = new UserViewModel();
mo.id = result.Id;
mo.WriterName = result.WriterName;
mo.WriterImage = result.ProfilePicture;
return View(mo);
}
此外,您可以将结果投影到UserViewModel并使其更简单/更短
var users=db.AspNetUsers.Where(s=>sId==id)
.Select(x=> new UserViewModel { Id=x.Id,
WriterImage =x.ProfileImage,
WriterName=x.WriteName}).ToList();
if(users.Any())
{
return View(users.First());
}
return Content("User not found");