2010-08-11 91 views
0

我試圖查詢與HQL的實體,以便返回對象的列表。查詢返回正確的行數,但第一個條目(即返回的第一行在所有實體中重複)。造成這個問題的原因是什麼?NHibernate的HQL加入查詢返回重複的實體列表

的HQL查詢

using (ISession session = NHibernateHelper.OpenSession()) 
    { 

    var query = session.CreateQuery(@" 
    select facts from Fact as facts 
    inner join facts.FactorDimension as facDim 
    inner join facts.MarketDimension as markDim 
    inner join facDim.TargetDimension as tarDim where 
    markDim.MarketID = :marketId 
    and tarDim.TargetID = :targetId 
    and facts.ReportYear = :untilReportYear 
    and facts.ReportMonth <= :untilReportMonth 
    and facts.ReportMonth >= 1 
    "); 

     query.SetString("targetId", targetId.ToString()); 
     query.SetString("marketId", marketId.ToString()); 
     query.SetString("untilReportMonth", untilPeriod.Month.ToString()); 
     query.SetString("untilReportYear", untilPeriod.Year.ToString()); 

    return query.List<Fact>(); 
    } 

和映射文件是

<class name="Fact" table="Fact"> 

     <composite-id> 
     <key-many-to-one name="MarketDimension" column="MarketID" 
class="MarketDimension"/> 
     <key-many-to-one name="FactorDimension" column="FactorID" class="FactorDimension"/>  
     </composite-id> 

     <property name="ReportMonth" /> 
     <property name="ReportYear" /> 

    </class> 

感謝。

回答

0

我設法通過執行以下操作來解決此問題。

表中有一個組合鍵用作主鍵,我刪除了組合鍵並添加了一個主鍵列。這種新的映射會導致查詢返回正確的實體。

如果任何人有任何解釋爲什麼會這樣,請添加一些評論。謝謝。

<class name="Fact" table="Fact"> 

     <id name="FactID"> 
     <generator class="guid"/> 
     </id> 

     <many-to-one name="MarketDimension" column="MarketID" class="MarketDimension"/> 
     <many-to-one name="FactorDimension" column="FactorID" class="FactorDimension"/>  


     <property name="ReportMonth" /> 
     <property name="ReportYear" /> 

    </class> 
1

指定查詢應該使用Transformer:DistinctRootEntityTransformer。

query.SetResultTransformer(Transformers.DistinctRootEntity);