简体   繁体   English

NHibernate-基于属性/列对实体进行排序+如何管理?

[英]NHibernate - Sorting Entities based on Property/Column + how to manage?

I'm writting an ASP.NET MVC e-commerce app using NHibernate and I want the end-user to be able to control the ordering of Product Categories (not just have them appear alphebetically etc.). 我正在使用NHibernate编写一个ASP.NET MVC电子商务应用程序,我希望最终用户能够控制产品类别的顺序(而不仅仅是让它们按字母顺序出现,等等)。

Normally, I'd add an OrderIndex/Sort column (of type int ) to the Category table, and property to the Category domain class. 通常,我会将OrderIndex / Sort列(类型为int )添加到Category表,并将属性添加到Category域类。 But the problem is in having to constantly manage this special OrderIndex/Sort column as Categories are sorted, added, and deleted. 但是问题在于,必须在分类,添加和删除类别时不断管理此特殊的OrderIndex / Sort列。 I'd rather hide it away and make it transparent so callers don't have to set the property directly. 我宁愿将其隐藏起来并使其透明,以便调用者不必直接设置该属性。

Sure I could write my own code to manage all this, but wanted to know if NHibernate has anything built in that could help me, or if it could hook this property up automatically. 当然,我可以编写自己的代码来管理所有这些内容,但是想知道NHibernate是否内置有任何可以帮助我的东西,或者它是否可以自动将该属性连接起来。

If not then I was thinking of creating an OrderedEntity base class (all domain objects derive from an Entity base), and create an IOrderedRepository base Repository as well. 如果不是,那么我正在考虑创建一个OrderedEntity基类(所有域对象都从Entity基派生),以及创建一个IOrderedRepository基知识库。 Something like this: 像这样:

public class Entity
{
    public virtual int Id { get; set; }
}

public class OrderedEntity : Entity
{
    public virtual int OrderIndex { get; set; }
}

public class Category : OrderedEntity
{

}

public interface IRepository<T> where T : Entity
{
    T FromId(int id);
    void Save(T entity);
}

public interface IOrderedRepository<T> : IRepository<T> where T : OrderedEntity
{
    void MoveUp(int places);
    void MoveDown(int places);
}

Does this seem like a good approach? 这似乎是一个好方法吗? I don't want to reinvent an inferior wheel. 我不想改造劣质的车轮。

So far I know Hibernate has an annotation @OrderBy where you can specify the ordering when the collection is loaded . 到目前为止,我知道Hibernate的注释为@OrderBy ,您可以在其中指定加载集合时的排序。 But Hibernate won't manage the position that for you when you add or remove element in the collection. 但是,当您addremove集合中的元素时,Hibernate将无法为您管理位置。

You can however easily do that yourself and provide methods addItem and removeItem on the parent entity , which will keep track of the position (or the methods MoveUp and MoveDown as you suggest). 但是,您可以自己轻松地完成此操作,并在父实体上提供方法addItemremoveItem ,以跟踪位置(或根据您的建议跟踪MoveUpMoveDown方法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM