NHibernate - 基于属性/列对实体进行排序 +怎么管理?
我正在使用 NHibernate 编写一个 ASP.NET MVC 电子商务应用程序,我希望最终用户能够控制产品类别的排序(而不仅仅是让它们按字母顺序显示等)。
通常,我会将 OrderIndex/Sort 列(类型为 int
)添加到 Category 表,并将属性添加到 Category 域类。但问题是在对类别进行排序、添加和删除时必须不断管理这个特殊的 OrderIndex/Sort 列。我宁愿将其隐藏起来并使其透明,这样调用者就不必直接设置该属性。
当然,我可以编写自己的代码来管理所有这些,但想知道 NHibernate 是否内置了任何可以帮助我的东西,或者它是否可以自动连接此属性。
如果没有,那么我正在考虑创建一个 OrderedEntity 基类(所有域对象都派生自实体基类),并创建一个 IOrderedRepository 基存储库。像这样的事情:
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);
}
这看起来是个好方法吗?我不想重新发明一个劣质的轮子。
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.).
Normally, I'd add an OrderIndex/Sort column (of type int
) to the Category table, and property to the Category domain class. But the problem is in having to constantly manage this special OrderIndex/Sort column as Categories are sorted, added, and deleted. 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.
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. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
到目前为止,我知道 Hibernate 有一个注释
@OrderBy
,您可以在其中指定集合加载时的顺序。但是当您在集合中添加
或删除
元素时,Hibernate不会为您管理位置。不过,您可以自己轻松地做到这一点,并在父实体上提供方法
addItem
和removeItem
,这将跟踪位置(或方法MoveUp
和MoveDown
按照您的建议)。So far I know Hibernate has an annotation
@OrderBy
where you can specify the ordering when the collection is loaded. But Hibernate won't manage the position that for you when youadd
orremove
element in the collection.You can however easily do that yourself and provide methods
addItem
andremoveItem
on the parent entity, which will keep track of the position (or the methodsMoveUp
andMoveDown
as you suggest).