获取对象引用未设置为对象的实例。来自Linq的错误

时间:2016-02-23 20:16:03

标签: entity-framework linq

我将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);
    }

请帮帮我。非常感谢你

1 个答案:

答案 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");