Union with NHibernate and Criteria?
Asked Answered
C

3

1

Union with NHibernate and Criteria:

Is it possible in Criteria or QueryOver? If not, is there any other way to achieve a union of two result within the same query?

Carbamidine answered 21/12, 2011 at 14:15 Comment(0)
D
6

You can't do a union directly, but you can do two future queries and union the results in code:

var resultSet1 = this.Session.CreateCriteria<A>().Future<A>();
var resultSet2 = this.Session.CreateCriteria<B>().Future<B>();

After this, when either result set is enumerated, NHibernate will issue a single query to the database which will return multiple result sets. Note, if you are not using SQL Server, the database may not support multiple result sets.

Dissenter answered 21/12, 2011 at 22:57 Comment(0)
M
6

This is not possible even using HQL. See this other S.O. post

One way is to drop back to raw SQL and use a named query

<sql-query name="MyQuery">
<![CDATA[
select col1,col2 from table1
union
select col1,colA from table2
]]>
</sql-query>

And use the AliasToBeanResultTransformer to transform it back into your DTO/POCO

var query = Session
  .GetNamedQuery("MyQuery")
  .SetResultTransformer(new AliasToBeanResultTransformer(typeof(MyDto)));
  return query.List<MyDto>();
Multifid answered 21/12, 2011 at 14:24 Comment(1)
Thats is unfortunately not an option since the columns can vary. Thanks for the tip though! +1Carbamidine
D
6

You can't do a union directly, but you can do two future queries and union the results in code:

var resultSet1 = this.Session.CreateCriteria<A>().Future<A>();
var resultSet2 = this.Session.CreateCriteria<B>().Future<B>();

After this, when either result set is enumerated, NHibernate will issue a single query to the database which will return multiple result sets. Note, if you are not using SQL Server, the database may not support multiple result sets.

Dissenter answered 21/12, 2011 at 22:57 Comment(0)
P
3

You can use -

NHibernate.Criterion.Restrictions.Or(ICriterion FirstQuery,
                                     ICriterion SecondQuery)

as your Criteria in a single query.

Pasty answered 21/12, 2011 at 15:39 Comment(2)
I'll try this in the morning and get back to youCarbamidine
This also works, but since i do an OR-clause with the base class and the cross table i join with (which i should have explained in the question), the resulting query results in a significant performance penalty. Thanks for the answer though. +1Carbamidine

© 2022 - 2024 — McMap. All rights reserved.