entity framework - Get Object reference not set to an instance of an object. Error from Linq -
this question has answer here:
- what nullreferenceexception, , how fix it? 33 answers
i object reference not set instance of object. error
here code:
public actionresult profile(string id) { news_application.newsdatabaseentities db = new news_application.newsdatabaseentities(); var result = (from u in db.aspnetusers 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 me. thank much
i think linq query giving null condition have. trying access property values of result
without checking whether null or not
public actionresult profile(string id) { var db = new news_application.newsdatabaseentities(); var result = (from u in db.aspnetusers u.id == id select new { u.id, u.writername, u.profilepicture }).firstordefault(); if(result==null) { return content("no records matching condition"); //to : change not found view. } userviewmodel mo = new userviewmodel(); mo.id = result.id; mo.writername = result.writername; mo.writerimage = result.profilepicture; return view(mo); }
also may project result userviewmodel , make 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");
Comments
Post a Comment