我收到以下代码的错误。
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。
答案 0 :(得分:0)
如果Contact
或Contact.Addresses
为null
,您忘记了第二部分:
您的专栏:
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>