gpt4 book ai didi

c# - NHibernate 3.2 QueryOver 按属性区分

转载 作者:行者123 更新时间:2023-11-30 21:10:08 25 4
gpt4 key购买 nike

我有两个类(class)

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

但结果我的列表中有很多重复的新闻。我认为这可能是因为在映射中启用了连接并在查询中使用了连接。那么,是否有任何解决方案如何通过一个属性或另一种方式进行区分来避免这个问题?

最佳答案

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

如文档中所述。

关于c# - NHibernate 3.2 QueryOver 按属性区分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8647468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com