views:

94

answers:

1

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.

+1  A: 

Criteria is probably not the best API for this... HQL is easier:

var fooDTOs = session.CreateQuery(@"
              select foo as Foo,
                     count(elements(foo.Bars)) as BarCount
              from Foo foo
              group by foo.id, foo.ImportantNumber
              ")
              .SetResultTransformer(Transformers.AliasToBean<FooDTO>())
              .List<FooDTO>();
Diego Mijelshon
Thanks, that certainly works and helps. I'm still holding out for a criteria based solution since I would later like to `CriteriaTransformer.TransformToRowCount` that summary to do pagination on it in a single unit. If nothing comes along in a couple of days I'll certainly award you the "accepted answer", until then I'll give you an up vote at least.
kaa