2009-05-02 72 views
0

我有實體食譜,它有一個HasMany集合評論。NHibernate排序有很多集合

在MVC控制器操作中,我獲得配方 ,然後顯示註釋。

如何按「EnteredOn」的降序對評論進行排序?

我在哪裏排序呢?

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

馬爾科姆

回答

2

我想,我只想找回評論原樣(不格外排序),然後只是排序配方的意見收集,顯示你的意見了。

取決於你如何創建你的類和你的映射,我認爲這是集合和包映射以來唯一的方式,代表NHibernate中的無序集合。

事情是這樣的:

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

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

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

凡我Reciple實體看起來是這樣的:

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

和映射:

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