NHibernate 3.2 QueryOver distinct by property

我只是一个虾纸丫 提交于 2019-12-24 02:59:14

问题


I have two classes

public class News
{
    public virtual int Id { get; protected set; }
    public virtual string Topic { get; set; }
    public virtual Category Category { get; set; }
}

public class Category
{
     public virtual int Id { get; protected set; }
     public virtual string Name { get; set; }
     public virtual ISet<News> News { get; set; }
}

And mappings

 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="News" namespace="NewsManagement.Models">
     <class name="News" table="News">
        <id name="Id">
             <generator class="native" />
         </id>
         <property name="Date" not-null="true" />
         <many-to-one name="Category" fetch="join" column="CategoryId" class="Category, NHibernateManyToOne" not-null="true"/>
     </class>
 </hibernate-mapping>

 <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="News" namespace="NewsManagement.Models">
     <class name="Category" table="Categories">
         <id name="Id" column="Id">
             <generator class="native" />
         </id>
         <set name="News" fetch="join" cascade="all-delete-orphan">
             <key column="CategoryId" />
             <one-to-many class="News, NHibernateOneToMany" /> 
         </set>
     </class>
 </hibernate-mapping>

And i want to take paged news, sorted by its category's name. Here is the query:

Session.QueryOver<News>().JoinQueryOver(x => x.Category).OrderBy(x => x.Name).Asc.Skip(pageNumber*pageSize).Take(pageSize).List<News>();

But in result i take many duplicated news in my list. I think it's probably because of joins both enabled in mappings and used in query. So, is there any solution how to do distinct by one property or another way to avoid this problem?


回答1:


You can implement your own IEqualityComparer and add it to your query like this.

class MyEqualityComparer : IEqualityComparer<News>
{
    public bool Equals(News x, News y)
    {
        return x.Id == y.Id;
    }

    public int GetHashCode(News obj)
    {
        return obj.Id.GetHashCode();
    }
}

And then use it like this

 Session.QueryOver<News>().JoinQueryOver(x => x.Category).List<News>()
            .Distinct(new MyEqualityComparer())
            .OrderBy(x => x.Category.Name).Skip(pageNumber * pageSize).Take(pageSize).ToList();

Consider fixing your join so you don't get duplicates adding .Left to your join.

Session.QueryOver<News>().Left.JoinQueryOver(x => x.Category)

As described in the documentation.

  • NHibernate Reference Documentation


来源:https://stackoverflow.com/questions/8647468/nhibernate-3-2-queryover-distinct-by-property

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