值不能为null参数名称:System.Linq.Enumerable.Select中的source [TSource,TResult]

时间:2018-04-10 05:28:30

标签: c# entity-framework entity-framework-core ef-core-2.0

我收到以下代码的错误。

var person = await context.Person.Where(x=>x.ID == 1).ToControllerModel().SignleOrDefaultAsync();

return person.ToViewModel();

static  IQueryable<Person> ToControllerModel(this IQueryable<Person> query)
        {
            return query.Select(i => new PersionModel{
                Name = i.Name,
                Addresses = (i.Contact != null && i.Contact.Addresses != null) ? i.Contact.Addresses.ToControllerModel() : null //causing error - works if removed
             });
        }


static  IQueryable<Address> ToControllerModel(this IQueryable<Address> query)
{
    return query.select( i => new AddressModel {
            Street = i.Street,
            No = i.No,
            City = i.City,
            Postcode = i.Postcode
   });
}

我尝试了不同的解决方案,以下似乎工作正常但不确定原因。任何人都可以解释为什么这会解决这个问题吗?

Addresses = (i.Contact != null && i.Contact.Addresses != null) ? i.Contact.Addresses.Select(x=>x.ToControllerModel())


static  Address ToControllerModel(this Address query)
{
    return  new AddressModel {
            Street = i.Street,
            No = i.No,
            City = i.City,
            Postcode = i.Postcode
   };
}

我正在使用EF Core。

1 个答案:

答案 0 :(得分:0)

如果ContactContact.Addressesnull,您忘记了第二部分:

您的专栏:

Addresses = (i.Contact != null && i.Contact.Addresses != null) ? i.Contact.Addresses.ToControllerModel()

正确的是:

Addresses = (i.Contact != null && i.Contact.Addresses != null) ? i.Contact.Addresses.ToControllerModel() : <provide default initalizer>