views:

53

answers:

1

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.

+1  A: 

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 you add or remove element in the collection.

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).

ewernli