简体   繁体   English

模型不为null时的空引用异常

[英]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 . 当我在Model上制作foreach ,一切都很好,但是当我尝试使用@Model.Count()来计算模型的项目时,我得到了Nullreference I'm getting Nullreference even when I copy my foreach just under the first one. 即使我在第一个复制我的foreach时,我也会得到Nullreference Any ideas what it can be? 有什么想法可以吗?

Even if you are sure your variables are not null: 即使您确定您的变量不为null:

If you are using FirstOrDefault , the returned value may be null, and therefore you must check it before accessing .Specialty : 如果您使用的是FirstOrDefault ,则返回的值可能为null,因此您必须在访问.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 . 由于@AlbinSunnanbo和他的答案在这里 I've got what i need. 我有我需要的东西。 Just executed my query by calling another ToList() ... 只是通过调用另一个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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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