外连接上的NullReferenceException

本文关键字:NullReferenceException 连接 | 更新日期: 2023-09-27 18:06:37

我试图从fderived抓取所有数据,但是我试图设置一个带有where子句的过滤器。不幸的是,当我触摸spd时,spd中的一行为空,我得到一个nullreferencexpectations。

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错误?

外连接上的NullReferenceException

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

尝试在where子句

中执行null检查
var Result = 
    ...
    where spd == null || spd.SId == "" || spd.PId == ""
    select new { fpd, spd };

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

LINQ双左连接

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