SQL Union to NHibernate Criteria

Alexandre Vicenzi picture Alexandre Vicenzi · Sep 4, 2013 · Viewed 8.8k times · Source

There's a way to convert this SQL statement to a NHibernate Criteria?

(select b1.FieldA as Name, b1.FieldA as FullName from Sale b1 where b1.FieldA like '%john%' or b1.FieldA like '%john%' order by b1.Id desc)
union 
(select b2.FieldC as Name, b2.FieldD as FullName from Sale b2 where b2.FieldC like '%john%' or b2.FieldD like '%john%' order by b2.Id desc)
union 
(select c.FieldE as Name, c.FieldF as FullName from Client c where c.FieldE like '%john%' or c.FieldF like '%john%' order by c.Id desc)

I've found that NHibernate doesn't support Unions.

Answer

Thierry picture Thierry · Sep 4, 2013

Try using a view. It can be mapped directly in NHibernate and does not rely on a specific database implementation. You should remove the where clauses, and then you can build your NHibernate criteria against "Name" and "FullName".

  (select b1.FieldA as Name, b1.FieldA as FullName from Sale b1 order by b1.Id desc)
  union 
  (select b2.FieldC as Name, b2.FieldD as FullName from Sale b2 order by b2.Id desc)
  union 
  (select c.FieldE as Name, c.FieldF as FullName from Client c order by c.Id desc)