“对象引用未设置为对象的实例”,即使我检查了null

时间:2013-07-13 19:06:59

标签: c# .net linq reference null

我有RoomBed个EF类,每个Room都有一些Bed s。当我使用这个LINQ语句时:

IEnumerable<Room> room=...
if (room == null || !room.Any())
    return null;
return room.SelectMany(r=>r.Beds); 

给我这个错误:

  

对象引用未设置为对象的实例。

return行。

4 个答案:

答案 0 :(得分:14)

可枚举中的一个房间为空。这样做:

return room.Where(r => r != null)
           .SelectMany(r => r.Beds);

答案 1 :(得分:2)

我发现我的Collection Roomnull不是Room而且Beds null Room都没有Collection。问题是我的null return room.Where(r => r != null).SelectMany(r => r.Beds); 中至少有一项是{{1}}。所以根据 YK1 的回答,我应该使用:

{{1}}

答案 2 :(得分:1)

只有当房间有Beds == null时才会出错。

你说:“我只有一​​间带两张床的房间”,但问题还提到EF。

问题出在... IEnumerable<Room> room=...

当您的EF查询使用lazy loading时,即使有记录,Beds属性也将为null。

要获得完整的解决方案,您必须发布有关EF部分的所有详细信息:Code | DB first,查询,类型Context类,EF版本等。

使用最新版本的EF这种问题很少见,我猜你在查询中有一个ToList(),你不应该这样。

答案 3 :(得分:0)

您也可以尝试使用计数,如下所示:

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