在Entity Framework中选择可选导航属性的属性的正确方法是什么? [英] What is a correct way to select a property of optional navigation property in Entity Framework?
问题描述
选择可选导航属性实体框架的属性的正确方法是什么?
What is a correct way to select a property of optional navigation property entity framework?
我担心如果导航属性为null,那么当我尝试访问其(可选的导航属性)属性时,就会引发错误.
I am concerned that in case the navigation property will be null, then the error will be thrown when I try to access its (optional navigation property`s) property.
这是我尝试过的:
return await this.relatedCasesRepository
.GetAll()
.AsNoTracking()
.Where(rc => rc.FirstCaseId == caseId || rc.SecondCaseId == caseId)
.Select(rc => new RelatedCaseInfoDto
{
FirstCaseId = rc.FirstCaseId,
FirstCaseName = rc.FirstCase.Name,
SecondCaseId = rc.SecondCaseId,
SecondCaseName = rc.SecondCase.Name,
CaseRelationTypeId = rc.CaseRelationTypeId,
CaseRelationTypeName = rc.CasesRelationType?.Name,
Id = rc.Id
})
.ToArrayAsync();
代码:rc.CasesRelationType?.Name
产生错误:
表达式树lambda不得包含空传播运算符.
An expression tree lambda may not contain a null propagation operator.
这是否意味着我应该执行第二个请求以获取可选导航属性的所有属性?还是有一种方法可以查询可选导航属性的属性,以防可选导航属性不为null,否则返回null?
Does that mean that I should perform a second request to get all the properties of the optional navigation property? Or is there a way to query the optional navigation property`s property in case the optional navigation property is not null and return null otherwise?
推荐答案
为什么不使用条件运算符?
Why not use a conditional operator?
CaseRelationTypeName = (rc.CasesRelationType != null) ? rc.CasesRealtionType.Name : null;
这篇关于在Entity Framework中选择可选导航属性的属性的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!