Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing NHibernate to select entities based on activity of children entities
    primarykey
    data
    text
    <p>I'm having a case of the Mondays...</p> <p>I need to select blog posts based on recent activity in the post's comments collection (a Post has a <code>List&lt;Comment&gt;</code> property and likewise, a Comment has a Post property, establishing the relationship. I don't want to show the same post twice, and I only need a subset of the entities, not all of the posts.</p> <p>First thought was to grab all posts that have comments, then order those based on the most recent comment. For this to work, I'm pretty sure I'd have to limit the comments for each Post to the first/newest Comment. Last I'd simply take the top 5 (or whatever max results number I want to pass into the method).</p> <p>Second thought would be to grab all of the comments, ordered by CreatedOn, and filter so there's only one Comment per Post. Then return those top (whatever) posts. This seems like the same as the first option, just going through the back door.</p> <p>I've got an ugly, two query option I've got working with some LINQ on the side for filtering, but I know there's a more elegant way to do it in using the NHibernate API. Hoping to see some good ideas here.</p> <p>EDIT: Here's what's working for me so far. While it works, I'm sure there's a better way to do it...</p> <pre><code>// get all comments ordered by CreatedOn date var comments = Session.CreateCriteria(typeof(Comment)).AddOrder(new Order("CreatedOn", false)).List&lt;Comment&gt;(); var postIDs = (from c in comments select c.ParentPost.ID).Distinct(); // filter the comments List&lt;Post&gt; posts = new List&lt;Post&gt;(); foreach(var postID in postIDs) { var post = Get(postID); // get a Post by ID if(!posts.Contains(post)) // this "if" is redundant due to the Distinct filter on the PostIDs collection { posts.Add(post); } } return posts; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload