【问题标题】:NullReferenceException on outer join外连接上的 NullReferenceException
【发布时间】:2013-03-21 18:11:49
【问题描述】:

我正在尝试从 Fderive 中获取所有数据,但是我正在尝试使用 where 子句设置过滤器。不幸的是,当我在 spd 中的一行为空时触摸 spd 时,我得到一个 nullreferencexpection。

var Result = from fpd in FDerive
                             join spd in SDerive
                             on new { fpd.PId, fpd.SId }
                             equals new { spd.PId, spd.SId } into allRows
                             from spd in allRows.DefaultIfEmpty()
                             where spd.SId == ""
                             || spd.PId == ""
                             select new { fpd, spd };

如何解决 null 错误?

【问题讨论】:

  • 这里需要右连接还是内连接?
  • 还有。您正在检查它们是否为空,您不应该检查它们是否为空吗?
  • 我想这是我的问题,我试图检查空行程的一切都是空错误。仍在寻找正确的组合来检查 null

标签: c# linq nullreferenceexception


【解决方案1】:

DefaultIfEmpty<T> 将返回一个集合,该集合仅包含一个默认值为 T 的元素 - 在本例中为 null - 如果源集合为空。因此,如果连接中没有返回任何项目,spd 将是 null

尝试在 where 子句中检查 null

var Result = 
    ...
    where spd == null || spd.SId == "" || spd.PId == ""
    select new { fpd, spd };

【讨论】:

【解决方案2】:

我在下面问题的代码底部找到了答案

LINQ double left join

var results =
        from person in students
        join entry in subquery on person.FullName equals entry.AuthorFullName into personEntries
        from personEntry in personEntries.DefaultIfEmpty()
        orderby person.FullName
        select new
        {
            PersonName = person.FullName,
            BlogTitle = personEntry == null ? "" : personEntry.Title
        };

【讨论】:

    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多