tags:

views:

63

answers:

2

Let's say I have 3 tables: carts, baskets and eggs where a basket can contain many eggs and where carts contain many baskets. Each basket has a foreign key that maps to a cart and each egg has a foreign key that maps to a basket.

I need to return a table that contains these 3 columns:

Cart Name | Count of Baskets in Cart | Count of Eggs in Cart.

Each table is an EF and I'm using linq with VB.

So far, I have 2 queries: one that returns the columns Cart Name and Count of Basket and another one that returns Cart Name and Count of Eggs. How can I combine these two result tables so that I get the results in one table?

           Dim query1 = (From cart In myEntities.Carts
           Where cart.UserID = TheUserID
           Join baskets In myEntities.Baskets On baskets.CartID Equals cart.CartID
           Select cart.CartName, cart.baskets.Count()).Distinct()

           Dim query2 = (From cart In myEntities.Carts
           Where cart.UserID = TheUserID
           Join baskets In myEntities.Baskets On baskets.CartID Equals cart.CartID
           Select cart.CartName, baskets.Eggs.Count()).Distinct()

Thanks for your help.

A: 

If you have the relationship defined, you could just use the Count method on the nested entities.

var cartCounts = from c in myEntities.Carts
                 select new 
                 { 
                     c.CartName, 
                     BasketCount = c.Baskets.Count(),
                     EggCount = c.Baskets.Eggs.Count() 
                 };
Dustin Laine
It basically tells me that Eggs is not a member. Can you see why?
You have a relationship setup between the baskets and eggs? Do both your queries work that you posted?
Dustin Laine
Yes, both queries work.
@Dustin Laine: `c.Baskets.Eggs.Count()` - here `Baskets` is a collection. You can't use `Baskets.Eggs`.
Yakimych
Good catch, looks like @jaraics has the right solution.
Dustin Laine
+1  A: 

The below query gives the desired result:

from cart in Carts _
select cart.CartName, BasketsInCart = cart.Baskets.Count(), EggsInCart = cart.Baskets.SelectMany(Function(basket)basket.Eggs).Count()

Because cart.Baskets is an Ienumerable(of Baskets) , the SelectMany operator can be used to get all the eggs from all the baskets.

jaraics
I modified the query to have the EggCount, the cartname, and the EggCount with your method: I should have 3 columns with the first and third giving the same results. However, the first column gives me the egg count per cart, the second column contains the same cart three times and then 2 cartnames that are empty, and the third column shows 5 counts, with the first 3 counts showing sums that I can't reproduce against the raw data and 2 zeros. There are 5 carts, 3 of them have eggs and 2 don't. ahhhhh, this is hairpulling at its peak!
I don't really understand what's the difference between the first and third column, and why do you need this setup? What you try to acomplish at the end?
jaraics