How to retrieve row count of one-to-many relation while also include original entity?

Posted by kaa on Stack Overflow See other posts from Stack Overflow or by kaa
Published on 2010-05-09T20:19:24Z Indexed on 2010/05/10 3:08 UTC
Read the original article Hit count: 215

Say I have two entities Foo and Bar where Foo has-many Bar's,

class Foo {
  int ImportantNumber { get; set; }
  IEnumerable<Bar> Bars { get; set; }
}

class FooDTO {
  Foo Foo { get; set; }
  int BarCount { get; set; }
}

How can I efficiently sum up the number of Bars per Foo in a DTO using a single query, preferrably only with the Criteria interface.

I have tried any number of ways to get the original entity out of a query with ´SetProjection´ but no luck. The current theory is to do something like

SELECT Foo.*, BarCounts.counts FROM Foo LEFT JOIN ( SELECT fooId, COUNT(*) as counts FROM Bar GROUP BY fooId ) AS BarCounts ON Foo.id=BarCounts.fooId

but with Criterias, and I just can't seem to figure out how.

© Stack Overflow or respective owner

Related posts about nhibernate

Related posts about criteria-api