Most succinct LINQ To SQL for taking COUNT(*) of either side of many-to-many?
-
04-07-2019 - |
Question
Please help me with a sanity check. Assuming a many-to-many relationship:
Post, PostTagAssoc, Tag http://www.codingthewheel.com/pics/many_to_many.gif
What's the most succinct way (using LINQ to SQL) to get a result set showing, for each tag (or post), the aggregate number of posts (or tags) assigned to it?
Thanks!
Solution
from pta in db.PostTagAssoc
group pta by pta.PostID into t
select new {PostID = t.Key, TagCount=t.Count()}
OTHER TIPS
This will also show those posts with 0 tags, and is a bit clearer in my opinion.
from p in db.Post
select new {PostID = p.ID, TagCount = t.PostTagAssoc.Count}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow