views:

161

answers:

1

I have a Product and Category entity in many-to-many association. I am trying to display the category count for each product. So far, I have come up with this:

Dim context = new Context()
Dim products = context.Products()
Dim productsByCategoryCount = From product In Products
 Group product By productId = product.productId Into productCount =  Count(product.cateogories.Count)

The query executes but doesn’t show the correct result. What am I doing wrong?

+3  A: 

A query like this should do it:

var results = from p in ctx.Products
              select new {Product = p, CategoryCount = p.Categories.Count}

Hope this helps

Alex

Alex James
Silly me, if you use Include it can be as easy as: For Each product In Products.Include("Categories") Console.WriteLine(product.Name + product.Categories.Count().ToString()Next
Dan
Yes you can do that too, but then you are loading every product and every category. If you just project the count you don't load the categories themselves. So it really depends on whether you need the categories or just the category count.
Alex James