执行编译表达式时出现NullReference异常

时间:2014-06-11 21:46:45

标签: c# entity-framework sql-server-2008-r2 linq-to-entities nullreferenceexception

我的表达式指定为:

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,

因为在这种情况下RequestAddressAddress实体可能为空。

其他实体看起来像这样

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; }
}

我尝试将检索CityProvince的部分更改为:

        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,

但这没有帮助。

0 个答案:

没有答案