如何将HQL结果转换为List <t>,其中T是映射类</t>

时间:2010-07-16 16:37:18

标签: nhibernate nhibernate-mapping hql

我有这个nhibernate查询:

var q =
               NHibernateSession.Current.CreateSQLQuery
               (
                    @"SELECT  LastestEvents.*
                    FROM    (
                            SELECT  DISTINCT SbQcontainer.Container
                            FROM    HistoricEvents
                            SbQcontainer WHERE SbQcontainer.LineCompany_Id = :lineCompany) as Sbq
                             JOIN HistoricEvents as  LastestEvents
                    ON      LastestEvents.id = (
                            SELECT TOP(1) id
                            FROM    HistoricEvents mi
                            WHERE   mi.Container = Sbq.Container and mi.LineCompany_Id = :lineCompany
                            ORDER BY mi.Date DESC
                            )"
               ).SetResultTransformer(Transformers.AliasToBean(typeof(HistoricEvent)));

            q.SetParameter("lineCompany",lineCompany.Id);
            q.SetCacheable(false);

            var results = q.List<HistoricEvent>().ToList();

它查找给定lineCompany的每个容器上的最新事件,它可以工作,但我不知道如何将此结果集设置为T HistoricEvent列表,我尝试这一行:

.SetResultTransformer(Transformers.AliasToBean(typeof(HistoricEvent)));

但抛出NHibernate.PropertyNotFoundException:找不到类'HistoricEvent'中属性'Event_Id'的setter。

有没有办法做到这一点?或者可能使用ICriteria API进行同样的查询?

提前谢谢。

1 个答案:

答案 0 :(得分:4)

假设HistoricEvent是一个映射实体,以下内容应该为您提供所需内容:

var q = 
               NHibernateSession.Current.CreateSQLQuery 
               ( 
                    @"SELECT  LastestEvents.* 
                    FROM    ( 
                            SELECT  DISTINCT SbQcontainer.Container 
                            FROM    HistoricEvents 
                            SbQcontainer WHERE SbQcontainer.LineCompany_Id = :lineCompany) as Sbq 
                             JOIN HistoricEvents as  LastestEvents 
                    ON      LastestEvents.id = ( 
                            SELECT TOP(1) id 
                            FROM    HistoricEvents mi 
                            WHERE   mi.Container = Sbq.Container and mi.LineCompany_Id = :lineCompany 
                            ORDER BY mi.Date DESC 
                            )" 
               ).AddEntity(typeof(HistoricEvent)); 

            q.SetParameter("lineCompany",lineCompany.Id); 
            q.SetCacheable(false); 

            var results = q.List<HistoricEvent>().ToList(); 

有关详细信息,请参阅relevant documentation