我正在尝试使用以下代码通过QueryOver
和RowCount
从员工那里获取所有活动任务:
var id = 1;
var activeTasks = Session
.QueryOver<Employee>()
.Where(emp => emp.id == id)
.JoinQueryOver<Tasks>(emp => emp.Tasks, JoinType.InnerJoin)
.Where(task => task.State == TaskState.Active)
.RowCount();
如果没有指定
id
的员工,则RowCount()
返回0
。问题是我需要知道员工是否不存在或是否没有活动任务。
我可以通过2个查询来做到这一点,首先查询该员工并检查是否为空,然后查询任务。但是理想情况下,如果可能的话,我希望将其全部放入一个查询中。
最佳答案
您可以使用LINQ to NHibernate轻松得多:
var employeeWithActiveTaskCount = session
.Query<Employee>()
.Where(e => e.Id == id)
.GroupJoin(
session
.Query<Task>()
.Where(t => t.State == TaskState.Active),
e => e.Id,
t => t.Employee.Id,
(e, t) => new { Employee = e, Tasks = t })
.Select(et => new
{
EmployeeId = et.Employee.Id,
TaskCount = et.Tasks.Count()
});
这将仅返回具有适当数量任务的现有员工。如果员工不存在,则返回空集合。由此生成的查询如下所示:
select employee0_.Id as col_0_0_, (select cast(count(*) as INT)
from [Task] task1_ where task1_.State=?
and (task1_.Employee_id=employee0_.Id
or (task1_.Employee_id is null)
and (employee0_.Id is null)))
as col_1_0_ from [Employee] employee0_ where employee0_.Id=?
关于c# - NHibernate QueryOver RowCount,区分0和NULL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49853563/