What is a correct way to select a property of optional navigation property in Entity Framework?

可紊 提交于 2020-03-25 16:12:52

问题


What is a correct way to select a property of optional navigation property entity framework?

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.

Here is what I tried:

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();

The code: rc.CasesRelationType?.Name produces an error:

An expression tree lambda may not contain a null propagation operator.

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?


回答1:


Why not use a conditional operator?

CaseRelationTypeName = (rc.CasesRelationType != null) ? rc.CasesRealtionType.Name : null;


来源:https://stackoverflow.com/questions/60317150/what-is-a-correct-way-to-select-a-property-of-optional-navigation-property-in-en

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!