LINQ to 实体查询,在使用导航之前检查 null 属性
LINQ to entity query, check null before using navigation property
请看这个简化的 LINQ 查询:
var lst = from pat in ctx.PATIENTS
join cons in ctx.CONSULTATIONS.Include(a => a.EXAMENS)
on pat.ID_PATIENT equals cons.CON_ID_PATIENT into joinpatcons
from p in joinpatcons.DefaultIfEmpty()
select new ConsultationsPageType()
{
ID_CONSULTATION = (p == null) ? 0 : p.ID_CONSULTATION
};
ID_CONSULTATION
字段可以为空 int
:
public class ConsultationsPageType
{
//......
public int? ID_CONSULTATION { get; set; }
//......
}
我想要的是 return null
而不是零,如果 p
是 null
。简单地用 null
替换 0
给了我这个错误:
Unable to determine the conditional expression type because there is
no implicit conversion between and intentre and int
并且 p?.ID_CONSULTATION
给了我这个错误:
A lambda expression arborecence can not contain a null propagation
operator
我正在使用 .NET 4.6。
您只需将零更改为 null
并将其转换为 int?
:
ID_CONSULTATION = (p == null ? (int?)null : p.ID_CONSULTATION)
请看这个简化的 LINQ 查询:
var lst = from pat in ctx.PATIENTS
join cons in ctx.CONSULTATIONS.Include(a => a.EXAMENS)
on pat.ID_PATIENT equals cons.CON_ID_PATIENT into joinpatcons
from p in joinpatcons.DefaultIfEmpty()
select new ConsultationsPageType()
{
ID_CONSULTATION = (p == null) ? 0 : p.ID_CONSULTATION
};
ID_CONSULTATION
字段可以为空 int
:
public class ConsultationsPageType
{
//......
public int? ID_CONSULTATION { get; set; }
//......
}
我想要的是 return null
而不是零,如果 p
是 null
。简单地用 null
替换 0
给了我这个错误:
Unable to determine the conditional expression type because there is no implicit conversion between and intentre and int
并且 p?.ID_CONSULTATION
给了我这个错误:
A lambda expression arborecence can not contain a null propagation operator
我正在使用 .NET 4.6。
您只需将零更改为 null
并将其转换为 int?
:
ID_CONSULTATION = (p == null ? (int?)null : p.ID_CONSULTATION)