【问题标题】:NHibernate transform sql query to NHibernate QueryOver queryNHibernate 将 sql 查询转换为 NHibernate QueryOver 查询
【发布时间】:2020-11-12 18:00:47
【问题描述】:

所以我有一些 SQL 查询,我不确定如何转换为 NHibernate 语法

cast(case when count(distinct order) > 1 then count(distinct order) * -1 else max(order.orderId) end as int)

我目前有以下 NHibernate 代码:

projectionList.Add(
    Projections.Conditional(
        Restrictions.Gt(Projections.CountDistinct(() => orderDto), 1),
            Projections.CountDistinct(() => orderDto), // TODO: * -1
            Projections.Max(() => orderDto.orderId)
    )
);

如您所见,我不确定* -1 部分该怎么做?有人知道怎么做吗?

【问题讨论】:

    标签: c# sql nhibernate


    【解决方案1】:

    您可以使用SQLFunctionTemplateProjections.SqlFunction 来表达任何需要投影参数的复杂SQL。在您的情况下,您可以执行以下操作:

        //All projections parameters in template are replaced with placeholders like ?1 ?2 ?3...
        //If possible move it to static field to avoid template parsing on each execution
        var yourTemplate = new SQLFunctionTemplate(
            NHibernateUtil.Int32, //Template result
            "cast(case when ?1 > 1 then ?1 * -1 else ?2 end as int)");
    
        //And in you query use the following projection:
        Projections.SqlFunction(
            yourTemplate,
            null, 
            Projections.CountDistinct(() => orderDto), //?1 in template
            Projections.Max(() => orderDto.orderId) //?2 in template
            ); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-27
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多