从NHibernate获得聚合结果的最佳方法是什么?

时间:2021-04-20 22:49:47

For example, I am trying to get a min date, a max date, and a sum in different instances. I am trying to avoid hard coding a SQL string or looping through an IList to get these values.

例如,我试图在不同的实例中获得最小日期,最大日期和总和。我试图避免硬编码SQL字符串或循环通过IList来获取这些值。

2 个解决方案

#1


2  

You can run straight queries through NHibernate. Or add additional order by info so the resulting objects are in order via the parameter you're interested in. Order descending and your 0th element is what you want for max and mins. etc etc. There's more than one way to skin the hibernating cat.

您可以通过NHibernate直接运行查询。或者按信息添加其他订单,以便通过您感兴趣的参数按顺序生成对象。顺序降序,您的第0个元素是您想要的最大值和分钟数。等等冬季猫的皮肤不止一种。

#2


2  

If you need queries for reporting, use projections.

如果您需要查询报告,请使用预测。

Something like:

Session.CreateCriteria ( typeof ( Order ) )
            .Add ( Restrictions.Between ( "DateReceived" , today.AddMonths ( -1 ) , today ) )
            .CreateAlias ( "Lines" , "lines" )
            .SetProjection (
            Projections.ProjectionList ( )
                .Add ( Projections.Sum ( "lines.TotalCost" ) )
                .Add ( Projections.Avg ( "lines.TotalCost" ) )
                .Add ( Projections.GroupProperty ( "Customer" ) )
            ) ;

There's more stuff in Nhibernate Documentation (it's 2/3 of the way down)

Nhibernate文档中有更多的东西(它是下降的2/3)

#1


2  

You can run straight queries through NHibernate. Or add additional order by info so the resulting objects are in order via the parameter you're interested in. Order descending and your 0th element is what you want for max and mins. etc etc. There's more than one way to skin the hibernating cat.

您可以通过NHibernate直接运行查询。或者按信息添加其他订单,以便通过您感兴趣的参数按顺序生成对象。顺序降序,您的第0个元素是您想要的最大值和分钟数。等等冬季猫的皮肤不止一种。

#2


2  

If you need queries for reporting, use projections.

如果您需要查询报告,请使用预测。

Something like:

Session.CreateCriteria ( typeof ( Order ) )
            .Add ( Restrictions.Between ( "DateReceived" , today.AddMonths ( -1 ) , today ) )
            .CreateAlias ( "Lines" , "lines" )
            .SetProjection (
            Projections.ProjectionList ( )
                .Add ( Projections.Sum ( "lines.TotalCost" ) )
                .Add ( Projections.Avg ( "lines.TotalCost" ) )
                .Add ( Projections.GroupProperty ( "Customer" ) )
            ) ;

There's more stuff in Nhibernate Documentation (it's 2/3 of the way down)

Nhibernate文档中有更多的东西(它是下降的2/3)