9

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
1
  • Just an observation with the SQL, but it seems that this is a bad way to get the data you require, shouldn't the sub select be replaced with a JOIN on the subordinate table, then a count(*) on it would result in the same value? It seems like you're forcing the query planner to take an inefficient route by doing the above. No hugely relevant to you're question, but it's what I'm looking for at the moment. Commented Nov 28, 2012 at 21:29

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

4 Comments

please let use know when it is available in Fluent.
While this works, I don't think it's efficient since you're running a subquery in your select clause. Is there a way to left join the child table with a group by in the main query?
I had to add () around the formula to get this to work for me, thanks for pointing me in the right direction
Extra Lazy Load is available in Fluent now... not sure when it was added, but just came across this question and thought I'd chip in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.