我正试图通过此代码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个查询执行此操作,我首先获取员工并检查null,然后查询任务。但理想情况下,如果可能的话,我希望这一切都在一个查询中。
答案 0 :(得分:1)
使用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=?