NHibernate Criteria: Subquery After 'From' Clause

杀马特。学长 韩版系。学妹 提交于 2019-12-02 02:45:18

问题


How can I write the following SQL using Criteria:

select b.Name as Batch, b.Capacity as Capecity, 
       a.tStudent as Admit, (b.Capacity-a.tStudent) as Availabe 
from ( 
 SELECT count(Id) as tStudent, BatchId FROM [dbo].[Student] group by BatchId) as a 
left join [dbo].[Batch] as b on a.BatchId = b.Id 

回答1:


To use NHibernate, to produce query like this:

SELECT ... 
FROM 
( 
 SELECT ...
) AS a 
..

We have to options:

  1. Map the sub-select as an Entity.
  2. create raw SQL query

The first option would mean to create some view, and map it as an Entity. If we do not like view (or cannot create it) we can use the power of NHibernate mapping, element <subselect>:

<class name="MyEntity"... >
   <subselect>
    SELECT ...
    FROM ...
   </subselect>
   ...

The second option is about using NHibernate API to create native/raw SQL:

session.CreateSQLQuery("SELECT ")

It is not profiting from mapping, but we can still apply parameters, and profit from transformation...

9.3.5. Queries in native SQL



来源:https://stackoverflow.com/questions/29739580/nhibernate-criteria-subquery-after-from-clause

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