tags:

views:

285

answers:

1

Hi,

I have entity Recipes and it has a HasMany collection comments.

In a MVC controller action I am getting the recipe and then displaying the comments.

How do I sort the comments in descending order of "EnteredOn"?

Where do I sort them?

  Recipe recipe = session.Load<Recipe>(id);
    NHibernateUtil.Initialize(recipe.Comments);

Malcolm

+2  A: 

I think I would just retrieve the comments as-is (not particulary sorted), and then just sort the Comments collection of the recipe, before you display the comments.

Depending on how you've created your class, and your mapping, I think this is the only way since a set and bag mapping, represent un-ordered collections in NHibernate.

Something like this:

Recipe recipe = session.Get<Recipe> (id);

var orderedComments = recipe.Comments.OrderBy ( comment => comment.EnteredOn );

foreach( Comment c in orderedComments )
{
   // display the comment
}

Where my Reciple entity looks something like this:

public class Recipe
{
   // ...
   ...

   private ISet<Comment> _comments = new HashedSet<Comment>();

   public ReadOnlyCollection<Comment> Comments
   {
      get { return _comments.ToList().AsReadOnly(); }
   }

   public void AddComment( Comment c )
   {
       if( c != null && !_comments.Contains (c) )
       {
          c.Recipe = this;
          _comments.Add (c);
       }
   }

   public void RemoveComment(Comment c )
   {
       if( c != null && _comments.Contains (c) )
       {
           c.Recipe = null;
           _comments.Remove(c);
       }
   }
}

and the mapping:

<class name="Recipe" table="Recipes">
    ...
    <set name="Comments" access="field.camelcase-underscore" ... >
        ...
    </set>
</class>
Frederik Gheysels