Search code examples
nhibernatenhibernate-criteria

Help with removing duplicates


I have asked a similar question 6 months ago that still has not been answer or any suggestions made.

Here is the problem. The code below is returning duplicate records. The actual returned record set I am working with is the Model.Product. The query is looking at the DateAdded field within ProductSkus table to see if the Product should show. The only problem is if more then 1 ProductSkus match the requirement for a particular Product I get duplicate records. I can't have this. I only care about accessing the data contained in Model.Product. Not Model.Product.ProductSkus.

Has anyone ran into a similar situation? Any ideas on how to get the results I am looking for?

Thanks in advance.

ICriteria query = this.Session.CreateCriteria<Model.Product>();
query.CreateAlias("ProductSkus", "ProdSku", JoinType.InnerJoin)
     .AddOrder(new Order("ProdSku.DateAdded", false))
     .AddOrder(new Order("Name", true))
     .Add(Restrictions.Ge("ProdSku.DateAdded", myDate))
     .SetMaxResults(100);

result = query.List();


Solution

  • You should make sure that your query/criteria uses a 'resultransformer'. In this case, you'll need the DistinctRootEntityResultTransformer.

     query.SetResultTransformer(Transformers.DistinctRootEntity);
    

    Next to that, how is that association mapped ? Is it mapped as a bag, or as a set ?