3

I have Room and Bed EF classes which each of Room have some Beds.when I use this LINQ statement:

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.

in return line.

4

4 回答 4

17

您的可枚举房间之一为空。做这个:

return room.Where(r => r != null)
           .SelectMany(r => r.Beds);
于 2013-07-13T19:45:03.603 回答
2

我发现 my Collectionof sRoom不是null,也没有一个是。问题是我的至少一项是。所以根据YK1的回答我应该使用:RoomBedsnullRoom Collectionnull

return room.Where(r => r != null).SelectMany(r => r.Beds);
于 2013-07-13T19:53:16.057 回答
1

只有当 Room 有Beds == null.

您说:“我只有一​​个房间,里面有两张床”,但问题还提到了 EF。

所以问题出在...in IEnumerable<Room> room=...

当您的 EF 查询使用延迟加载时,即使有记录,Beds 属性也将为空。

对于完整的解决方案,您必须发布有关 EF 部分的所有详细信息:首先是代码|DB、查询、上下文类的类型、EF 版本等。

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

于 2013-07-13T19:31:03.287 回答
0

您也可以尝试使用 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);
于 2013-07-13T19:18:09.530 回答