Linq OrderBy中断导航属性为null [英] Linq OrderBy breaks with navigation property being null
问题描述
使用四个表。
用户 - >具有基本的用户信息,包括一个用户ID和一个departmentid(int)
组 - >基本组信息,包括groupid
GroupsMembers - >表具有组与成员之间的关系,多对多关系,因此groupid和userid是列
Departments - > basic部门信息包括deptid
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
我有一个从用户表中的departmentid的fk到department表中的deparmtnet id。
I have a fk from the departmentid in the users table to the deparmtnet id in the departments table.
FK从group groupid到groupsmembers groupid
FK从用户userid到groupsmembers userid
FK from groups groupid to groupsmembers groupid FK from users userid to groupsmembers userid
这允许edmx中的组具有用户导航属性这将包含该组的所有成员。
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);
}
我正在包括Users.Department。
I am including Users.Department.
问题是因为用户不必拥有部门,所以departmentid列可以为空。如果departmentid为空的任何用户,则orderby中断并说u.Department为null。如果没有部门是空的,它的效果很好。我需要一种基于Department.Name进行排序的方法,即使有空的部门。任何建议?
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?
推荐答案
您可以使用条件运算符来检查部门是否为空:
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;
}
可以使用如下:
userQuery = userQuery.OrderBy(u => u.Department.IfNotNull(d => d.Name, String.Empty));
这篇关于Linq OrderBy中断导航属性为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!