Sti*_*ian 2 c# linq entity-framework-core
我正在尝试对可以具有任意数量的不同角色的员工列表进行排序.角色本身按SortOrder属性排序,我希望员工按照分配给他们的所有角色的最高排序进行排序.
例如:
SortOrder - Role
1 - "Manager"
2 - "Graphics designer"
3 - "Server-tech-guy"
4 - "Web developer"
5 - "Coffee Machine manager"
Run Code Online (Sandbox Code Playgroud)
员工既可以是图形设计师,也可以管理咖啡机.在这种情况下,我只想SortOrder在对员工列表进行排序时使用角色"图形设计器".
这是我的模特:
public class Employee
{
public int Id { get; set; }
public int BranchId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public double EmploymentPercentage { get; set; }
public double HourlyWage { get; set; }
public List<EmployeeRole> EmployeeRoles { get; set; }
public Branch Branch { get; set; }
}
public class EmployeeRole
{
public int Id { get; set; }
public int EmployeeId { get; set; }
public int RoleId { get; set; }
public Employee Employee { get; set; }
public Role Role { get; set; }
}
public class Role
{
public int Id { get; set; }
public string Title { get; set; }
public int SortOrder { get; set; }
public Branch Branch { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止的查询:
List<Employee> employees = await db.Employees
.Include(er => er.EmployeeRoles)
.ThenInclude(r => r.Role)
.Where(b => b.Branch.Id == BranchId)
.OrderByDescending(r => r.EmployeeRoles.Min(s => s.Role.SortOrder))
.ThenByDescending(p => p.EmploymentPercentage)
.ThenBy(n => n.LastName)
.ToListAsync();
Run Code Online (Sandbox Code Playgroud)
在这个查询中,我试图找到SortOrder每个员工的最低数量的角色(.Min(s => s.Role.SortOrder)但是它没有按照我的预期进行.我得到了
InvalidOperationException:Sequence不包含任何元素.
当源序列为空时(例如,如果有一些没有分配s),非可空重载Min和Max方法会抛出异常.EmployeeRole
但是,可以为空的重载不会抛出异常,而只是返回null.因此,解决方案是将非可空类型提升为相应的可空类型.另外,??运算符可用于为该情况指定特殊值.
在你的情况下,它可以是这样的:
.OrderByDescending(r => r.EmployeeRoles.Min(s => (int?)s.Role.SortOrder) ?? 0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |