how to do this with NHibernate criteria

蓝咒 提交于 2019-12-05 02:30:50

问题


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:


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>();



回答2:


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/



来源:https://stackoverflow.com/questions/2478858/how-to-do-this-with-nhibernate-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!