Search code examples
sqlnhibernatepostgresqlnhibernate-projections

How to build string query with NHibernate?


I would like to reproduce this query with NHibernate using projection

SELECT ('reword#' || reword) || reword_faq as foo FROM me_review_entries re
WHERE ('reword#' || reword) || reword_faq = 'reword#2#SOME_FAQ'

I did

Session.CreateCriteria<Reword>

But then I don't know I could do projection to build the string ('reword#' || reword) || reword_faq

Any Idea ?


Solution

  • I am not familiar with postGreSQL at all but hopefully this might be close to what you need.

    var results = session.CreateCriteria<Reword>()
        .SetProjection(Projections.ProjectionList()
          .Add(Projections.Property("reword"), "reword")
          .Add(Projections.Property("faq"), "faq")
        )
      .Add(Restrictions.Eq("reword","2"))
      .Add(Restrictions.Eq("faq","SOME_FAQ"))
      .SetResultTransformer(new AliasToBeanResultTransformer(typeof(ReWordDTO)))
      .List<ReWordDTO>();
    

    You can then concat the columns from the DTO in code for output if needed. You might need to add some OR conditions to make it work in Criteria.

    Should produce SQL like this:

    select Reword, Reword_faq
    from me_review_entries
    where reword=2
    and reword_faq='SOME_FAQ'
    

    Which is similar to your original query and might be close to what you are looking for. I'm not sure you need to concat the columns in your where clause seeing as you have the values separately already.

    Your original:

    SELECT ('reword#' || reword) || reword_faq as foo FROM me_review_entries re
    WHERE ('reword#' || reword) || reword_faq = 'reword#2#SOME_FAQ'
    

    Could it be re-written as?:

    SELECT (reword || reword_faq) as foo 
    FROM me_review_entries re
    WHERE  (reword || reword_faq) = '2#SOME_FAQ'
    

    Which could then be re-written as?:

    SELECT (reword || reword_faq) as foo 
    FROM me_review_entries re
    WHERE  reword=2 and reword_faq='#SOME_FAQ'
    

    Although the data in the columns might mean it needs to be written the way you describe. You could add some OR conditions into the criteria query to make it work if that is the case.

    Another option would be to register a CustomSQLFunction.

    RegisterFunction("concat", 
      new SQLFunctionTemplate(NHibernateUtil.String, "(?1 || ?2)"));
    

    Registering Custom SQL Functions in NHibernate

    var results = session.CreateQuery("select concat(reword,rewordfaq) 
      from Reword
      where concat(reword,rewordfaq)='2#SOME_FAQ'
    ").List();