简体   繁体   中英

Nullreference exception when the model is not null

Today i faced strange exception. I have two tables in my DB, that have some linked columns. According to my app's logic i have to make an update on select and send updated list to my view. So, I act like this:

return View(repo.Enrollee.ToList().Select(p => {
               p.SpecialtyCode =  repo.EnrolleePlaces.FirstOrDefault(t => 
               t.SpecialtyCode == p.SpecialtyCode).Specialty; 
               return p; 
               }).OrderByDescending(p => p.Update));

When I make foreach on Model everything is Ok, but when I try to count model's items, using @Model.Count() , I get the Nullreference . I'm getting Nullreference even when I copy my foreach just under the first one. Any ideas what it can be?

Even if you are sure your variables are not null:

If you are using FirstOrDefault , the returned value may be null, and therefore you must check it before accessing .Specialty :

p.SpecialtyCode =  repo.EnrolleePlaces.FirstOrDefault(t => 
t.SpecialtyCode == p.SpecialtyCode).Specialty;

You may use the following:

var someVar = repo.EnrolleePlaces.FirstOrDefault(t => t.SpecialtyCode == p.SpecialtyCode);
p.SpecialtyCode =  someVar == null? null : someVar.Specialty;

Thanks to @AlbinSunnanbo and his answer here . I've got what i need. Just executed my query by calling another ToList() ...

So, that's the answer:

return View(repo.Enrollee.ToList().Select(p => {
               p.SpecialtyCode =  repo.EnrolleePlaces.FirstOrDefault(t => 
               t.SpecialtyCode == p.SpecialtyCode).Specialty; 
               return p; 
               }).OrderByDescending(p => p.Update).ToList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM