【问题标题】:LINQ DefaultIfEmpty issue on object with non-nullable value type property具有不可空值类型属性的对象的 LINQ DefaultIfEmpty 问题
【发布时间】:2012-09-17 00:03:17
【问题描述】:

要求

  1. 我需要加入Table1和Table2
  2. 两个表之间的键是ID,它是System.Guid类型,是不可为空的值类型
  3. 如果 Table2.ID 为空,我需要从 Table1 中获取空记录。

我写的LINQ语法如下。

from records in DBContext.Table1
join history in DBContext.Table2 into recordhistory
from records in recordhistory.DefaultIfEmpty()
select (n => n);

我得到的错误是“无法将空值分配给 System.Guid 类型的成员,这是一个不可为空的值类型。”

有人可以给我建议吗?非常感谢。

【问题讨论】:

  • "如果 Table2.ID 为 null,我需要从 Table1 中获取 null 记录" 什么意思:可以有没有 ID 的历史记录吗?或者你的意思是没有历史记录的Table1记录,如果是这样,不要选择Table1记录?

标签: c# linq defaultifempty


【解决方案1】:

假设您有一个 ID 属性,以下应该作为内部连接:

var result = DBContext.Table1
              .Join(DBContext.Table2, t1 => t1.ID, t2 => t2.ID, (t1, t2) => t1);

【讨论】:

  • 最后一部分是什么? (t1,t2)=>t1
  • 即返回结果的记录。如果需要,可以在这里构造一个新对象,它可以包含 t1 和 t2 的组合属性;例如新的 MyResult() { Property1 = t1.ID, Property2 = t2.Value }
【解决方案2】:

我猜,你提供的查询应该给出一个错误,说应该指定on 语句。所以,我想它应该看起来像这样:

from records in DBContext.Table1
join history in DBContext.Table2 on records.ID equals history.ID into temp
from recordhistory in temp.DefaultIfEmpty()
select new { Record = records, History = recordhistory };

【讨论】:

    猜你喜欢
    • 2015-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2010-09-19
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多