NHibernate 3.2 QueryOver按属性区分

本文关键字:属性区 QueryOver NHibernate | 更新日期: 2023-09-27 18:18:56

我有两个类

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; }
}

映射
 <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>

我想取按类别名称排序的分页新闻。下面是查询:

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

但结果我在我的列表中有许多重复的新闻。我认为这可能是因为连接在映射和查询中都启用了。那么,有没有一种方法可以避免这个问题呢?

NHibernate 3.2 QueryOver按属性区分

你可以实现你自己的IEqualityComparer,并像这样将它添加到你的查询中。

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();
    }
}

然后像这样使用

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

考虑修复你的连接,这样你就不会得到重复添加.Left到你的连接。

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

如文档所述。

  • NHibernate参考文档