Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map count of collection to entity with fluent-nhibernate

With employees and subordinates - I want to load an employee with the count of subordinates in one query.

public class Employee
{
    public Name {get;set;}
    public int NumberOfSubordinates {get;set;}
}

Resulting SQL should look like :

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
like image 937
W3Max Avatar asked Feb 20 '10 02:02

W3Max


1 Answers

You could map this column as a Formula.

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

A different approach is to map Subordinates as an inverse bag and use lazy="extra". In this case Subordinates.Count will perform the SQL count(*), though not as part of the initial load. This approach may not yet be available in Fluent.

like image 57
Lachlan Roche Avatar answered Sep 28 '22 17:09

Lachlan Roche