如何使用Fluent-nhibernate将集合计数映射到实体

W3M*_*Max 9 collections nhibernate fluent-nhibernate

对于员工和下属 - 我想在一个查询中加载具有下属数量的员工.

public class Employee
{
    public Name {get;set;}
    public int NumberOfSubordinates {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

生成的SQL应如下所示:

select e.name, (select count(*) from subordinate s where s.employee_id = e.id) NumberOfSubordinates
from employee e 
group by e.name
order by NumberOfSubordinates desc
Run Code Online (Sandbox Code Playgroud)

Lac*_*che 15

您可以将此列映射为公式.

Map(x => x.NumberOfSubordinates)
    .FormulaIs(@"select count(*) from subordinate where subordinate.employee_id = id");
Run Code Online (Sandbox Code Playgroud)

另一种方法是将Subordinates映射为反向包并使用lazy ="extra".在这种情况下,Subordinates.Count将执行SQL count(*),但不作为初始加载的一部分.这种方法可能尚未在Fluent中提供.