Union with NHibernate and Criteria?

瘦欲@ 提交于 2019-12-23 02:59:09

问题


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?


回答1:


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.




回答2:


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



回答3:


You can use -

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

as your Criteria in a single query.



来源:https://stackoverflow.com/questions/8591200/union-with-nhibernate-and-criteria

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!