ChevCast
ChevCast

Reputation: 59224

Using LINQ to get one entity with the most of a child entity

I have an entity in Entity Framework 4 called Topic. Topic has a navigation property to a collection of Reply entities.

I am trying to craft a query that obtains the most popular topic based on the number of replies.

entityContainer.Topics.Single(x => x./* has the most replies of any topic */);

I'm not sure how to craft a query to accomplish this.

Upvotes: 3

Views: 114

Answers (1)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59131

This might accomplish what you're looking to do.

var mostPopularTopic = entityContainer.Topics
    .OrderByDescending(t => t.Replies.Count())
    .FirstOrDefault();

if(mostPopularTopic != null) // If there were any topics...
{
    // ...
}

I imagine this is going to have terrible perf, tho.

A better option might be to denormalize your data (slightly) and add a reply count column to the Topic table. Then you can index that column, and do a simple sort and retrieve for row. This will avoid a whole table scan of Topics and a count (at query time) on every Replies entry.

The trade-off will be that you have to be careful to ensure that the Replies count always gets updated, or live with results that aren't always completely up to date and do a background job to rebuild these values.

Upvotes: 5

Related Questions