NHibernate如何将此SQL查询转换为QueryOver或Linq

时间:2012-09-01 18:33:42

标签: nhibernate queryover

我真的可以使用一些指导如何将这个SQL查询带到NHibernate QueryOver。我尝试使用Linq,因为我对Linq更熟悉。我们正在研究的项目是使用QueryOver,所以最好现在就保持这条路线。

工作SQL查询:将DateTime重绕为1分钟并正确分组/排序/计数......

select dateadd(minute,(datediff(minute,0,dateTimeColumn)/1)*1,0), COUNT(*)
from PartData
group by dateadd(minute,(datediff(minute,0,dateTimeColumn)/1)*1,0)
order by dateadd(minute,(datediff(minute,0,dateTimeColumn)/1)*1,0)

返回预期结果:

2012-08-31 00:00:00.000, 3
2012-08-31 00:01:00.000, 4
2012-08-31 00:02:00.000, 3
2012-08-31 00:03:00.000, 3
2012-08-31 00:04:00.000, 4
2012-08-31 00:05:00.000, 3
2012-08-31 00:06:00.000, 3
2012-08-31 00:07:00.000, 4
2012-08-31 00:08:00.000, 3

修改

我越来越近了......

private IQueryOver<entities.PartData, entities.PartData> PartPerHourQuery(ISession session)
{
    return session.QueryOver<entities.PartData>()
        .Select(
            Projections.Alias(
                Projections.GroupProperty(
                    Projections.SqlFunction(
                        new SQLFunctionTemplate(NHibernateUtil.DateTime, "DateAdd(mm,1,Date)"),
                        NHibernateUtil.DateTime, _partsDate))
                , "Date"),
            Projections.Alias(Projections.RowCount(), "Count"))
                .TransformUsing(Transformers.AliasToBean<entities.PartsPerHour>());
}

产生以下SQL:

SELECT DateAdd(mm,1,dateTimeColumn), count(*)
FROM [PartData] 
GROUP BY DateAdd(mm,1,dateTimeColumn)

只需要弄明白如何在那里找到日期:)

1 个答案:

答案 0 :(得分:7)

通过坚持不懈的力量,我成功赢得了这场战斗。这是我上面提到的SQL查询的QueryOver ......我相信我已经在这个NHibernate的事情上转了一个角落:)

非常感谢任何改进或替代方法重新产生预期结果的建议。

private IQueryOver<entities.PartData, entities.PartData> PartPerHourQuery(ISession session)
{
    return session.QueryOver<entities.PartData>()
        .Select(
            Projections.Alias(
                Projections.GroupProperty(
                    Projections.SqlFunction(
                        new SQLFunctionTemplate(NHibernateUtil.DateTime, "DateAdd(minute," +
                                                                         new SQLFunctionTemplate(
                                                                             NHibernateUtil.DateTime,
                                                                             "(DateDiff(minute, 0, Date)/1)*1") +
                                                                         ",0)"),
                        NHibernateUtil.DateTime, _partsDate))
                , "Date"),
            Projections.Alias(Projections.RowCount(), "Count"))
        .TransformUsing(Transformers.AliasToBean<entities.PartsPerHour>());
}