我有以下代码
return (EseshEntities.Current.Users.Select(u => new { Comunity = u.Apartment.Building.District.City })).ToList();
如果建筑物是空的那么我们得到了excpetion cos无法访问null的属性吧? 但是在实体中有任何选项,只有null的excpetion返回,所以如果属性 不存在然后返回null?
答案 0 :(得分:2)
这是怎么回事?
return (EseshEntities.Current.Users.Select(u => new { Comunity = u.Apartment.Building ==null?null:u.Apartment.Building.District.City })).ToList();
答案 1 :(得分:1)
您可以尝试这样的事情:
var list = (from u in EseshEntities.Current.Users
where u.Apartment.Building != null
select new { Comunity = u.Apartment.Building.District.City }).ToList();
return list;
或者你可以试试这个:
return (EseshEntities.Current.Users.Select(u => new { Comunity = u.Apartment.ToInstance().Building.ToInstance().District.ToInstance().City })).ToList();
public static T ToInstance<T>(this T self)
{
T mySelf = default(T);
if (self != null)
mySelf = self;
else
mySelf = Activator.CreateInstance<T>();
return mySelf;
}