【发布时间】:2018-01-29 16:12:18
【问题描述】:
我正在尝试使用导航属性编写 linq 查询。我正在从 3 个实体中选择属性:
- 储物柜
- 节列
- 合同
我需要 Lockers 表中满足以下所有条件的所有行:LockerTypeId = "308", .OutOfOrder != true, x.SectionColumn.SectionId == "52")。
下面没有条件 x.SectionColumn.SectionId == "52" 的查询可以正常工作,并准确返回我需要的内容,除了我所期望的返回任何值的 Section id 的行。
from l in Lockers.Where(x => x.LockerTypeId == "308" && x.OutOfOrder !=
true).DefaultIfEmpty()
select new
{
ColumnNumber = l.ColumnNumber,
LockerTypeId = l.LockerTypeId,
OutOfOrder = l.OutOfOrder,
Rented = l.Contracts.Select(x => x.Contract_ID < 0 ?
false : true).FirstOrDefault(),
Section = l.SectionColumn.SectionId
}
当我如下添加条件 'x.SectionColumn.SectionId == "52"' 时,我收到错误“转换为值类型 'System.Int32' 失败,因为具体化值为 null”。结果类型的泛型参数或查询必须在 linqpad 中使用可空类型”。SectionId 是字符串(SQL Server 中的 varchar)。
from l in Lockers.Where(x => x.LockerTypeId == "308" && x.OutOfOrder !=
true).DefaultIfEmpty()
如果能帮助我正确编写此查询,我将不胜感激。
【问题讨论】:
-
请编辑第二个代码示例。那里没有
SectionId。 -
Section = l.SectionColumn != null?l.SectionColumn.SectionId?0:0
-
如果 SectionColumn 在表架构中允许为空?
-
在访问 l.SectionColumn.SectionId 之前,您必须检查 l.SectionColumn is not equal null
标签: c# entity-framework linq lambda linq-to-entities