我的表达式指定为:
private static Expression<Func<Request, RequestResultModel>> requestResultExpression = request =>
request.Applicant
.ApplicantAddresses
.DefaultIfEmpty()
.OrderBy(address => address.IsPreferred)
.Select(address => new RequestResultModel
{
Id = request.Id,
ApplicantName = request.Applicant.FullName,
ReviewerName = request.Reviewer.FullName,
RefferrerName = request.Refferrer.Name,
City = address.Address.City,
Province = address.Address.Province.Code,
DisciplineCode = request.Discipline.Code,
Event = request.Event,
StatusName = request.Status.Name,
Submitted = request.Submitted
})
.FirstOrDefault();
我也重复使用相同的表达式:
private static Func<Request, RequestResultModel> requestResultFunction = requestResultExpression.Compile();
不幸的是,当Request.Applicant
没有ApplicantAddresses
时,当我执行这样的代码时,我得到NullReferenceException
:
var entity = this.DbContext.Requests.Find(id);
var model = requestResultFunction(entity);
问题在于:
City = address.Address.City,
Province = address.Address.Province.Code,
因为在这种情况下RequestAddress
或Address
实体可能为空。
其他实体看起来像这样
public class Applicant
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<ApplicantAddress> ApplicantAddresses { get; set; }
}
public class ApplicantAddress
{
[Key]
public int Id { get; set; }
public virtual Applicant { get; set; }
public virtual Address { get; set; }
public bool IsPreferred { get; set; }
}
public class Address
{
[Key]
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public virtual Province Province { get; set; }
public string PostalCode { get; set; }
public virtual ICollection<ApplicantAddress> ApplicantAddresses { get; set; }
}
public class Province
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
}
我尝试将检索City
和Province
的部分更改为:
City = address == null || address.Address == null ? null : address.Address.City,
Province = address == null || address.Address == null || address.Address.Province == null ? null : address.Address.Province.Code,
但这没有帮助。