开发者

linq count with join on multiple tables

开发者 https://www.devze.com 2023-01-19 05:45 出处:网络
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 fore

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'开发者_Go百科m using linq. It's a combination of joins and counts and I'm moving in circles.

Thanks for your help.


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()
}
0

精彩评论

暂无评论...
验证码 换一张
取 消