I'm having a case of the Mondays...
I need to select blog posts based on recent activity in the post's comments collection (a Post has a List<Comment>
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.
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).
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.
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.
EDIT: Here's what's working for me so far. While it works, I'm sure there's a better way to do it...
// get all comments ordered by CreatedOn date
var comments = Session.CreateCriteria(typeof(Comment)).AddOrder(new Order("CreatedOn", false)).List<Comment>();
var postIDs = (from c in comments select c.ParentPost.ID).Distinct();
// filter the comments
List<Post> posts = new List<Post>();
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;