Linq OrderBy breaks with navigation property being null
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));