score:17

Accepted answer

One of your rooms in the enumerable is null. Do this:

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

score:0

You can try to use count too, like this:

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

score:1

The error can only happen when a Room has Beds == null.

You state: "I only have one Room with two Beds in it" but the question also mentions EF.

So the problem is in the ... in IEnumerable<Room> room=....

When your EF query uses lazy loading the Beds property will be null even if there are records.

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.

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.

score:2

I found out that my Collection of Rooms were not null and also none of Room's Beds were null. problem was that at least one item of my Room Collection was null. so according to YK1's answer I should use:

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

Related Articles