NHibernate HQL join query for list of entities returning duplicates
I am attempting to query entities with HQL in order to return a list of objects. The query returns the correct number of rows, but the first entry (ie the first row returned is duplicated across all entities). What could be the cause of this problem?
The HQL query is
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.开发者_C百科Month.ToString());
query.SetString("untilReportYear", untilPeriod.Year.ToString());
return query.List<Fact>();
}
and the mapping file is
<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>
Thanks.
Specify that the query should use a Transformer: the DistinctRootEntityTransformer.
query.SetResultTransformer(Transformers.DistinctRootEntity);
I managed to resolve this by doing the following.
There is a composite key in the table being used as a primary key, I removed the composite key and added a single primary key column. This new mapping results in the correct entities being returned from the query.
If anyone has any explanation as to why this would be the case please add some comments. Thanks.
<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>
精彩评论