views:

29

answers:

1

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 columns:

-Cart Name -Number of Baskets in Cart -Number of Eggs in cart.

Each table is an EF and I'm using linq. It's a combination of joins and counts and I'm moving in circles.

Thanks for your help.

+2  A: 

I am a LINQ-to-SQL man myself, but I believe EF auto-generates one-to-many properties as IEnumerables, so this should work for you:

from cart in Carts
select new
{
    CartName = cart.Name,
    BasketCount = cart.Baskets.Count(),
    EggCount = cart.Baskets.SelectMany(b => b.Eggs).Count()
}
Ian Henry
Yes, this will work, as long as he has Navigational Properties in his EDMX. Otherwise he'll have to explicitly join on the FK's.
RPM1984
I'm using EF so for instance I can write (VB) dim myResult = from carts in myEntities.Cart; if that clarifies's RPM1984's comment.
This works fantastically well with LINQ to SQL and is also very fast performance wise. Wow you saved me some hell and sped my page up about ten fold by switching to this method. LINQ must optimise this really well behind the scenes as I have bulk data just appearing instantly all with the correct counts after using this method. Cheers!
Aaron