Linq OrderBy breaks with navigation property being null

僤鯓⒐⒋嵵緔 提交于 2019-12-03 11:00:12

问题


Working with four tables.

Users -> has basic user info including a userid and a departmentid (int)
Groups -> basic group info including a groupid
GroupsMembers -> table that has the relationship between a group and it's members, many to many relationship, so groupid and userid are the columns
Departments -> basic department info including deptid

I have a fk from the departmentid in the users table to the deparmtnet id in the departments table.

FK from groups groupid to groupsmembers groupid FK from users userid to groupsmembers userid

This allows the groups in the edmx to have a users navigation property which will have all the members of the group.

var grp = grpSource.FirstOrDefault(g => g.GroupID == groupID)
if (grp.GroupID > 0)
{
    var userQuery = from u in grp.Users
                    where !u.Deleted
                    select u;
    userQuery = userQuery.OrderBy(u => u.Department.Name);
}

I am including Users.Department.

The problem comes because users do not have to have a department, so the departmentid column is nullable. If there are any users for which the departmentid is null, the orderby breaks and says u.Department is null. If no departmentids are null, it works great. I need a way to sort based on Department.Name even if there are null departmentids. Any suggestions?


回答1:


You can use the conditional operator to check if the department is null :

userQuery = userQuery.OrderBy(u => (u.Department != null) ? u.Department.Name : String.Empty);

For improved clarity, I created the following extension method :

    public static TResult IfNotNull<TSource, TResult>(this TSource obj, Func<TSource, TResult> selector, TResult defaultValue)
    {
        if (obj != null)
            return selector(obj);
        return defaultValue;
    }

It can be used as follows :

userQuery = userQuery.OrderBy(u => u.Department.IfNotNull(d => d.Name, String.Empty));



回答2:


How about using the coalesce operator?

userQuery = userQuery.OrderBy(u => u.Department.Name ?? string.Empty);


来源:https://stackoverflow.com/questions/2290436/linq-orderby-breaks-with-navigation-property-being-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!