【问题标题】:LINQ query returns null reference only after adding where clauseLINQ 查询仅在添加 where 子句后才返回空引用
【发布时间】:2015-06-25 21:10:59
【问题描述】:

我在一个方法中有 2 个链接的 LINQ 查询。第一个从具有“Person XXXX-XXXX 被标记为已删除”形式的表行中获取一个子字符串,并提取 XXXX-XXXX 部分并将它们放入包含 XXXX-XXXX 的对象中。

var ids = from m in _repo.GetMessages()
                       where m.tool == 7
                       select new IDs
                       {
                           ID = m.text.Substring(6, 11),
                           text = m.text
                       };

这会按预期返回数据。然后这些 id 加入到后续的“结果”查询中:

var results = from gs in _repo.GetSample()
                          join c in _repo.Getcenters() on gs.Iid equals c.Iid_c
                          join id in ids on gs.id equals id.ID
                          select new Results
                          {
                              c_id = c.id,
                              iid_d = gs.Iid_d,
                              Id = gs.id,
                              Num = gs.num,
                              sts_dt = c.sts_dt,
                              store_dte = gs.Store_dte,
                              quantity = gs.Quantity
                          };

这种形式的查询返回预期的数据,但我需要在结果查询中添加 where 子句。当我添加一个引用查询中任何数据对象的 where 子句时,输出会产生“对象引用未设置为对象的实例”。如果没有 where 子句,一切看起来都很好。

我的第一个想法是空项目存在于第一个数据集中,所以我添加了一个 != null 子句,它没有任何效果。然后我尝试用 Contains(ID) 语句替换连接 ID,但这并没有改变。由于我之前编写过许多链接的 LINQ 查询并以这种方式将它们链接起来没有问题,我的猜测是 ID 对象上的连接可能会导致一些奇怪的事情。有没有人知道如何在不产生错误的情况下添加 where 子句?谢谢!

【问题讨论】:

  • 您能否提供一个带有导致问题的 where 子句的语句示例?
  • 希望您在 Select 之前使用 Where 子句...
  • 是的,我将 where 子句放在 join 和 select 之间。执行此操作的语句示例(我尝试过的每个语句都会导致错误): where gs.quantity > 0

标签: c# .net sql-server linq


【解决方案1】:

在搞砸了一段时间后,我决定尝试将 2 个查询连接在一起,这似乎解决了问题。为什么我一开始不这样做,我不确定,但我猜测连接到上一个查询的输出触发了一个空对象警告。以下查询可以正常工作:

var results = from gs in _repo.GetSample()
                      join c in _repo.Getcenters() on gs.Iid equals c.Iid_c
                      join ids in _repo.GetLogs() on gs.id equals ids.text.Substring(6,11)
                      where gs.quantity > 0
                      select new Results
                      {
                          c_id = c.id,
                          iid_d = gs.Iid_d,
                          Id = gs.id,
                          Num = gs.num,
                          sts_dt = c.sts_dt,
                          store_dte = gs.Store_dte,
                          quantity = gs.Quantity
                      };

这也是一个更好、更紧凑的查询。谢谢大家!

【讨论】:

    【解决方案2】:

    试试from gs in _repo.GetSample().Where(s=>s.quantity>0) ...

    【讨论】:

    • 不幸的是,这给了我同样的结果。
    猜你喜欢
    • 2011-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    相关资源
    最近更新 更多