QueryOver查找别名字符串

时间:2012-08-07 09:46:19

标签: c# sql-server nhibernate fluent-nhibernate

我有下一个聚合查询:

   IQueryOver<CustomerTask, CustomerTask> query = GetSession().QueryOver(() => task)
    .JoinAlias(() => task.TaskList, () => taskList)
    .JoinAlias(() => task.TaskChain, () => taskChain)
    .Where(() => taskList.SalesFlow == salesFlow)
    .Select(
        Projections.Group(() => taskList.Id)
            .WithAlias(() => salesFlowTaskStatisticsGridRow.RowId),
        Projections.Group(() => taskList.SalesFlow.Id)
            .WithAlias(() => salesFlowTaskStatisticsGridRow.SalesFlowId),
        Projections.Group(() => taskList.Name).WithAlias(() => salesFlowTaskStatisticsGridRow.Name),
        // ReSharper disable ExpressionIsAlwaysNull
        criteriaBuilder.FindAverageCompletionTime(salesFlowTaskStatisticsGridRow)
    // ReSharper restore ExpressionIsAlwaysNull
    ).TransformUsing(Transformers.AliasToBean<SalesFlowTaskStatisticsGridRow>());

由于计算平均时间需要调用datediff函数来编写它我使用SqlProjection

    private static AggregateProjection CountAverageCompletionTimeForTasksCriteria()
    {
        return Projections.Avg(Projections
            .SqlProjection("datediff(ss, Created, CompletedDate) as CompletionTimeInSeconds",
                new[] {"CompletionTimeInSeconds"}, new[] {NHibernateUtil.Double}));
    }

问题是任务 TaskChain 对于已创建已完成日期属性具有相同的名称,因此我需要传递一个别名。但我无法设法获取字符串别名以形成正确的SQL投影。有没有办法获得这些别名,还是可以通过其他方式将 datediff 函数添加到查询中?

1 个答案:

答案 0 :(得分:0)

使用SqlProjection时,NHibernate没有提供很多复杂的选项来处理别名。

唯一的解决方法是首先分析查询而不使用datediff投影,并查看NHibernate为Task和TaskChain使用的别名(它们可能类似于 this _ 和* this_1 *)。然后,您可以手动将这些别名硬编码到投影中,如下所示:

.SqlProjection("datediff(ss, this_.Created, this_.CompletedDate) as CompletionTimeInSeconds",
                new[] {"CompletionTimeInSeconds"}, new[] {NHibernateUtil.Double})

显然这远非完美,但它会起作用。