c# - 如何使用 Nhibernate 进行条件求和?

标签 c# queryover nhibernate-3

我正在尝试执行与此 SQL 代码等效的操作

SELECT 
ID
SUM(CASE WHEN myProperty = 2 THEN 1 ELSE 0 END) as nbRowWithValueOf2,
SUM(CASE WHEN myProperty = 3 THEN 1 ELSE 0 END) as nbRowWithValueOf3
FROM Foo
GROUP BY ID

使用 Nhibernate。

到目前为止我已经尝试过了

queryable = queryable
    .Select(
        Projections.Group<Foo>(c => c.ID),
        Projections.Sum<Foo>(c => c.myProperty == MyEnum.Two ? 1 : 0)
        Projections.Sum<Foo>(c => c.myProperty == MyEnum.Three ? 1 : 0)
)

但这给了我以下错误:

Could not determine member from IIF((Convert(c.myProperty) = 2), 1, 0)

你有什么想法吗?

编辑 1:我可以通过 2 个查询获得结果,但我只想在 1 个查询中执行此操作。

编辑 2:我在这里使用 QueryOver。

最佳答案

我认为这应该可行(QueryOver 语法):

queryover = queryover
    .Select(
        Projections.Group<Foo>(c => c.ID),
        Projections.Sum(
            Projections.Conditional(
                Restrictions.Where<Foo>(f => f.myProperty == MyEnum.Two),
                Projections.Constant(1),
                Projections.Constant(0))),
        Projections.Sum(
            Projections.Conditional(
                Restrictions.Where<Foo>(f => f.myProperty == MyEnum.Three),
                Projections.Constant(1),
                Projections.Constant(0))));

它应该给你下面的 SQL:

SELECT this_.ID as y0_,
       sum((case
              when this_.myProperty = 2 /* @p0 */ then 1 /* @p1 */
              else 0 /* @p2 */
            end))               as y1_,
       sum((case
              when this_.myProperty = 3 /* @p3 */ then 1 /* @p4 */
              else 0 /* @p5 */
            end))               as y2_
FROM   [Foo] this_
GROUP  BY this_.ID

关于c# - 如何使用 Nhibernate 进行条件求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9774345/

相关文章:

c# - 分解 XML 文件 C# 中的所有元素

c# - 如果我返回它创建的数组,新的本地类实例会被垃圾回收吗?

c# - 如何在asp.net中的下拉列表中绑定(bind)数据库中的选定值

c# - NHibernate QueryOver 两次加入一个集合

nhibernate - 如何将 Skip 和 Take 附加到 nHibernate IQueryOver

mysql - 具有相同标识符值的不同对象已与实体的 session : XXX, 关联

c# - 如何将我的列表<>分组

c# - 流畅的 nhibernate 字符串到枚举选择查询示例

nhibernate - 使用NHibernate和QueryOver联接多个表

c# - NHibernate 3 使用冗长的语法指定 sql 数据类型