1

I get Object reference not set to an instance of an object. error

here is my code:

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

Please help me. Thank you so much

Lucia
  • 203
  • 5
  • 22
  • 3
    Where? What's the stack trace? I note you're using `FirstOrDefault()`, which means if there are no matches, `result` will be `null`... but you're unconditionally dereferencing it... – Jon Skeet Feb 23 '16 at 20:19

1 Answers1

0

I think your LINQ query is giving you NULL for the where condition you have. But you are trying to access the property values of result without checking whether it is null or not

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

Also you may project your result to the UserViewModel and make it more simple/short

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");
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • I tried your code and it's working after i put if(result==null) but it didn't tell me No records matching the where condition while the same code told me before i put if(result==null) Object reference not set to an instance of an object.... the question is how to avoid that problem again? Thank you so much – Lucia Feb 23 '16 at 20:34