NHibernate QueryOver CASE WHEN计算列值

时间:2015-05-27 12:39:46

标签: select nhibernate case queryover

我一直在尝试在NHibernate QueryOver中执行以下T-SQL,但没有成功:

SELECT Id, SUM(CASE MyValue WHEN 1 THEN Volume ELSE Volume * -1 END)
FROM MyTable
GROUP BY Id

我试图总结所有音量,但MyValue=1应为正值,否则为负值。到目前为止,我得到了:

 var result = this.Session.QueryOver<MyTable>()
    .Select(Projections.Group<MyTable>(x => x.Id),
    Projections.Conditional(Restrictions.Eq(Projections.Property<MyTable>(x
        => x.MyValue), '1'),
    Projections.Property<MyTable>(x => x.Volume),
    Projections.Property<MyTable>(x => x.Volume * -1)))
    .List();

但是你可以想象NHibernate不知道列Volume * -1,那么如何在我的CASE中进行这个计算?

1 个答案:

答案 0 :(得分:3)

我认为这应该可以解决问题:

session.QueryOver<MyTable>()
    .Select(
        Projections.Group<MyTable>(x => x.Id),
        Projections.Sum(
            Projections.Conditional(
                Restrictions.Eq(
                    Projections.Property<MyTable>(x => x.MyValue), 1),
                Projections.Property<MyTable>(x => x.Volume),
                Projections.SqlFunction(
                    new VarArgsSQLFunction("(", "*", ")"),
                    NHibernateUtil.Int32,
                    Projections.Property<MyTable>(x => x.Volume),
                    Projections.Constant(-1)))))
    .List<object[]>();

通常,QueryOver在算术方面非常糟糕。据我所知,你必须使用VarArgsSQLFunction来构建乘法表达式。

这将生成以下SQL:

SELECT
    this_.Id as y0_,
    sum((
        case when this_.MyValue = 1 
        then this_.Volume else (this_.Volume*-1) end
    )) as y1_
FROM        
    MyTable this_     
GROUP BY        
    this_.Id

请注意,您需要在此处使用与自定义DTO配对的结果转换器,或使用.List<object[]>,这会将结果集转换为List object[],每个项目都在List是结果行。你不能只使用.List(),因为NHibernate希望选择整个MyTable行,你没有在这里做。

你可能认为这很丑陋,我同意。您可以通过将投影重构为自己的变量来清理它:

IProjection multiplicationProjection = 
    Projections.SqlFunction(
        new VarArgsSQLFunction("(", "*", ")"),
        NHibernateUtil.Int32,
        Projections.Property<MyTable>(t => t.Volume),
        Projections.Constant(-1));

IProjection conditionalProjection = 
    Projections.Conditional(
        Restrictions.Eq(
            Projections.Property<MyTable>(t => t.MyValue), 1),
        Projections.Property<MyTable>(t => t.Volume),
        multiplicationProjection);

session.QueryOver<MyTable>()
    .SelectList(list => list
        .SelectGroup(t => t.Id)
        .Select(Projections.Sum(conditionalProjection)))
    .List<object[]>();