简体   繁体   中英

Force Entity to return null if singleResult throw exception

I have following code

return (EseshEntities.Current.Users.Select(u => new { Comunity = u.Apartment.Building.District.City })).ToList();

if building is empty then we got excpetion cos can't acces property of null right? but is there any option in entity to instad of excpetion return just null, so if property doesn't exist then return null?

那这个呢?

return (EseshEntities.Current.Users.Select(u => new { Comunity = u.Apartment.Building ==null?null:u.Apartment.Building.District.City })).ToList();

You can try something like this:

var list = (from u in EseshEntities.Current.Users
            where u.Apartment.Building != null
            select new { Comunity = u.Apartment.Building.District.City }).ToList();
return list;

or you can try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM