【问题标题】:"Object reference not set to an instance of an object" even when I checked null“对象引用未设置为对象的实例”即使我检查了 null
【发布时间】:2013-07-13 19:06:59
【问题描述】:

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

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

给我这个错误:

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

在return 行中。

【问题讨论】:

  • 所以可能至少有 1 个房间带有Beds==null
  • 思维不够好,你应该知道。或找出答案。
  • @HenkHolterman 我只有一个Room 和两个Beds
  • 您的代码看起来不错,不应出现此错误。所以尝试在一个小而完整的程序中重现它,我们也可以运行它。您很可能会在此过程中自己找到原因。

标签: c# .net linq reference null


【解决方案1】:

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

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

【讨论】:

  • 对我来说是return room.Where(r =&gt; r.Beds != null) .SelectMany(r =&gt; r.Beds);
  • 有人知道为什么会这样吗?它在做 room.Select(x => x.beds) 时有效,当它有一个空值时,为什么 selectmany 没有?
【解决方案2】:

我发现我的Collection 和Room 不是null,而且Room 的Beds 也不是null。问题是我的Room Collection 中至少有一项是null。所以根据YK1的回答我应该使用:

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

【讨论】:

    【解决方案3】:

    只有当房间有Beds == null时才会发生错误。

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

    所以问题出在... 中的IEnumerable&lt;Room&gt; room=... 中。

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

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

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

    【讨论】:

    • 但是为什么if(!room.Any(x =&gt; x.Beds == null)) 给我同样的错误?
    • 我真的不知道。无法从您发布的内容中判断。
    【解决方案4】:

    你也可以尝试使用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);
    

    【讨论】:

    • 检查了很多,但真正的原因可能是什么?
    • count() == 0 将取代 !room.Any() 我相信。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2019-03-08
    相关资源
    最近更新 更多