Dunadan
Dunadan

Reputation: 23

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?

Upvotes: 1

Views: 203

Answers (2)

Dunadan
Dunadan

Reputation: 23

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

Upvotes: 0

Yosi Dahari
Yosi Dahari

Reputation: 7009

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;

Upvotes: 3

Related Questions