简体   繁体   中英

NHibernate transform sql query to NHibernate QueryOver query

So I have a bit of a SQL query which I am not sure how to convert to NHibernate syntax

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

I currently have the following NHibernate code:

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

As you can see, I am not sure how to do the * -1 part? Has somebody any idea how to do it?

You can use SQLFunctionTemplate and Projections.SqlFunction to express any complex SQL that needs projection parameters. In your case you can do something like this:

    //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
        ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM