I\'ve been wondering about this one for a while now, so I thought it would be worth using my first Stack Overflow post to ask about it.
Imagine I have a discussion with
If this isn't a one off, and you find yourself needing to count a number of different associated entities, a database view might be a simpler (and potentially more appropriate) choice:
Create your database view.
Assuming you want all of the original entity properties plus the associated message count:
CREATE VIEW DiscussionCategoryWithStats AS
SELECT dc.*,
(SELECT count(1) FROM Messages m WHERE m.DiscussionCategoryId = dc.Id)
AS MessageCount
FROM DiscussionCategory dc
(If you're using Entity Framework Code First Migrations, see this SO answer on how to create a view.)
In EF, simply use the view instead of the original entity:
// You'll need to implement this!
DiscussionCategoryWithStats dcs = _repository.GetDiscussionCategoryWithStats(id);
int i = dcs.MessageCount;
...