LINQ Join:对象引用未设置为对象的实例

LINQ Join: Object reference not set to an instance of an object

我有一个从 Linq 生成的列表到 SQL。为简单起见,它看起来像这样:

var myItems = (from my in db.MyTable
                select new
                {
                    UniqueID = my.ID,
                    UserName = my.UserName,
                    CreatedOn = my.CreatedOn
                }).ToList();

此列表包含 4 个项目。

我还有一个:

var grid = (from q in AnotherLinqQuery
                select new
                {
                    UniqueID = q.ID,
                    Department = q.Department,
                    Comments = q.Comments
                }).ToList();

此列表包含 20 个项目。 myItems 中的所有 ID 都显示在网格中。

现在我想用左连接将它连接起来。

var q = from A in grid
        from B in myItems.Where(x => x.UniqueID == grid.UniqueID).DefaultIfEmpty()
        select new 
        {
           UniqueID = A.UniqueID,
           Department = A.Department,
           CreatedOn = B.CreatedOn
        }

当我执行这个时,我得到

Object reference not set to an instance of an object.

我也尝试过其他连接,例如

from A in grid
            from B in myItems.Where(x => x.UniqueID != null && x.UniqueID == grid.UniqueID).DefaultIfEmpty()

您没有正确加入。试试这个:

var q = from A in grid
        join B in myItems on A.UniqueId equals B.UniqueId into LB
        from B in LB.DefaultIfEmpty()
        select new 
        {
            UniqueID = A.UniqueID,
            Department = A.Department,
            CreatedOn = B.CreatedOn
        };

您可能需要参考 documentation 以获取有关加入 linq 的更多信息。

由于您正在执行 左联接 而不是 内联接myItems 中将没有项目仅在 grid 中但不在 myItems.

中的 16 个元素 在这种情况下

B 将是 null(因为 DefaultIfEmpty() 创建一个包含一个 null 元素的序列),因此您必须检查 null 这里:

var q = from A in grid
        from B in myItems.Where(x => x.UniqueID == grid.UniqueID).DefaultIfEmpty()
        select new 
        {
           UniqueID = A.UniqueID,
           Department = A.Department,
           CreatedOn = B?.CreatedOn ?? DateTime.MinValue // or whatever default value you like
        }