NHibernate Projection查询按日期分组

时间:2010-12-08 20:45:00

标签: c# nhibernate criteria nhibernate-projections

我想在NHibernate中编写一个Projection查询,按日期对记录进行分组,并为这些记录计算“Tax”字段值。我的问题是数据库的值是DateTime,我如何按日期而不是时间对记录进行分组。这是我的代码

template.Criteria.SetProjection(
                Projections.ProjectionList()
                .Add(Projections.GroupProperty("IssueDatetime"), "DateVal")
                .Add(Projections.Sum("Tax"), "TotalFare")
            );

数据库将IssueDatetime字段存储为DateTime类型。我想计算每个日期的税,并忽略时间部分。有人可以帮我解决上述要求吗?

2 个答案:

答案 0 :(得分:8)

使用以下内容进行第一次投影:

Projections.GroupProperty(
    Projections.SqlFunction("date",
                            NHibernateUtil.Date,
                            Projections.GroupProperty("IssueDateTime")))

对于NH 2.x:

Projections.GroupProperty(
    Projections.SqlFunction(new SQLFunctionTemplate(
                                NHibernateUtil.Date,
                                "dateadd(dd, 0, datediff(dd, 0, ?1))"),
                            NHibernateUtil.Date,
                            Projections.GroupProperty("IssueDateTime")))

答案 1 :(得分:2)

假设SQL Server和T-SQL,此ICriteria将执行此操作。

IList results = Session.CreateCriteria(typeof(Record), "record")
    .SetProjection(Projections.ProjectionList()
        .Add(Projections.SqlGroupProjection("CONVERT(date, {alias}.[IssueDatetime]) AS [DateVal]", "CONVERT(date, {alias}.[IssueDatetime])", new[] { "DateVal" }, new IType[] { NHibernateUtil.Date }))
        .Add(Projections.Sum("Tax"), "TotalFare"))
    .List();

生成以下SQL。

SELECT CONVERT(date, this_.[IssueDatetime]) AS [DateVal], sum(this_.Tax) as y1_ FROM IgnoreTime_Record this_ GROUP BY CONVERT(date, this_.[IssueDatetime])