【发布时间】:2019-03-07 23:49:32
【问题描述】:
我有一个端点,它应该列出按搜索词过滤的所有候选人,所以我要做的是创建一个接受候选人实体和 searchTerm 作为参数的方法。然后我将该方法传递给 Where 子句,但问题是我得到了NullReferenceException,因为导航属性是空值。如果我将语句放在 Where 子句而不是方法中,那么它不会 throw Exception。问题是如何解决这个问题,但我想保留外部方法,因为会有更多逻辑,但我需要访问所有 navigation properties,即它们应该被填充。
if (!string.IsNullOrEmpty(searchTerm))
{
query = query.Where(c => FilterBySearchTerm(c, searchTerm));
}
var result = await query.Select(c => new CandidaturesResponseModel()
{
Id = c.Id,
Name = c.PrimaryMember.FullName, // that's filled
}).ToListAsync();
private bool FilterBySearchTerm(Candidature c, string searchTerm)
{
return c.PrimaryMember.FirstName.Contains(searchTerm); // here is the exception because PrimaryMember navigation property is null. So I want this to be filled.
}
【问题讨论】:
标签: c# asp.net-core entity-framework-core asp.net-core-webapi