Linq OrderBy breaks with navigation property being null

前端 未结 2 1536
春和景丽
春和景丽 2021-02-04 01:02

Working with four tables.

Users -> has basic user info including a userid and a departmentid (int)
Groups -> basic group info including a groupid
GroupsMembers -

相关标签:
2条回答
  • 2021-02-04 01:36

    How about using the coalesce operator?

    userQuery = userQuery.OrderBy(u => u.Department.Name ?? string.Empty);
    
    0 讨论(0)
  • 2021-02-04 01:50

    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));
    
    0 讨论(0)
提交回复
热议问题