NHibernate 3.2 QueryOver属性不同

时间:2011-12-27 17:31:13

标签: c# nhibernate queryover

我有两个班级

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

但结果我在我的列表中收集了许多重复的新闻。我认为这可能是因为在映射中启用了连接并在查询中使用了连接。那么,有没有解决方法如何通过一种属性或其他方式来区分这种问题?

1 个答案:

答案 0 :(得分:4)

您可以实现自己的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)

如文档中所述。