views:

63

answers:

2

let's say I have 2 tables table1(a,b) and table2(c,a)

I need to do something like this, but with NHibernate criteria:

select a,b, (select count(*) from table2 t2 where t1.a = t2.a ) x from table1 t1

anybody knows how to do this ?

+1  A: 

You could add a custom SQL statement by mapping a named query: http://www.sidesofmarch.com/index.php/archive/2009/02/11/executing-native-sql-using-nhibernate-named-queries/

statichippo
+3  A: 

with Projections.SubQuery

var l = session.CreateCriteria<Table1>("t1")
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.Property("a"), "a")
        .Add(Projections.Property("b"), "b")
        .Add(Projections.SubQuery(
            DetachedCriteria.For<Table2>("t2")
            .SetProjection(Projections.RowCount())
            .Add(Restrictions.EqProperty("t1.a", "t2.a"))), "x"))
    .SetResultTransformer(Transformers.AliasToBean<Table1WithTable2Count>())
    .List<Table1WithTable2Count>();
dotjoe