Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to do this with NHibernate criteria

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 ?

like image 929
Omu Avatar asked Feb 27 '23 08:02

Omu


1 Answers

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>();
like image 114
dotjoe Avatar answered Mar 08 '23 06:03

dotjoe