[英]"Object reference not set to an instance of an object" even when I checked null
I have Room
and Bed
EF classes which each of Room
have some Bed
s.when I use this LINQ statement:我有
Room
和Bed
EF 类,每个Room
都有一些Bed
s。当我使用这个 LINQ 语句时:
IEnumerable<Room> room=...
if (room == null || !room.Any())
return null;
return room.SelectMany(r=>r.Beds);
give me this error:给我这个错误:
Object reference not set to an instance of an object.
Object 引用未设置为 object 的实例。
in return
line.在
return
线。
One of your rooms in the enumerable is null. 可枚举中的一个房间是null。 Do this:
做这个:
return room.Where(r => r != null)
.SelectMany(r => r.Beds);
I found out that my Collection
of Room
s were not null
and also none of Room
's Beds
were null
. 我发现我
Collection
的Room
小号不null
也没有的Room
的Beds
是null
。 problem was that at least one item of my Room
Collection
was null
. 问题是我的
Room
Collection
中至少有一项是null
。 so according to YK1 's answer I should use: 所以根据YK1的回答,我应该使用:
return room.Where(r => r != null).SelectMany(r => r.Beds);
The error can only happen when a Room has Beds == null
. 只有当房间有
Beds == null
时才会发生错误。
You state: "I only have one Room with two Beds in it" but the question also mentions EF. 你说:“我只有一间带两张床的房间”,但问题还提到EF。
So the problem is in the ...
in IEnumerable<Room> room=...
. 所以问题出现在
...
IEnumerable<Room> room=...
。
When your EF query uses lazy loading the Beds property will be null even if there are records. 当您的EF查询使用延迟加载时 ,即使有记录,Beds属性也将为null。
For a complete solution you'll have to post all details about the EF part: Code|DB first, the query, which type Context class, EF version etc. 要获得完整的解决方案,您必须发布有关EF部分的所有详细信息:Code | DB first,查询,类型Context类,EF版本等。
With the latest versions of EF this kind of problem is rare, my guess is that you have a ToList()
in the query where you shouldn't. 使用最新版本的EF这种问题很少见,我的猜测是你在查询中有一个
ToList()
,你不应该这样。
You can try to use count too, like this: 您也可以尝试使用count,如下所示:
IEnumerable<Room> room=...
if (room == null) // Check for nulls
return null;
else if (room.count() == 0) // Check if empty
return null;
else if(!room.Any(x => x.Beds == null) // Check if there is no null Beds
return room.SelectMany(r=>r.Beds);
Please try this..请试试这个..
return room.Where(r => r != null & r.Beds != null).SelectMany(r => r.Beds);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.