开发者

How make LINQ query with GroupBy and LEFT JOIN

I'm using EF4 and i need to make this query with LINQ but i don't know how.

If i have 3 tables:

  • ProductType
  • Product
  • Season

ProductType -> one-to-many -> Product -> many-to-开发者_如何学Cone -> Season

i would like to have a list of all the ProductType with their Products for one Season. Please note that i need to list ALL the ProductType even if there's no Product inside for that Season.

thank you for the help!


Try this:

var query = from pt in model.ProductTypes
            join p in model.Product.Where(p => p.SeasonId == seasonId)
               on pt.Id equals p.ProductTypeId into g
            select new { ProductType = pt, Products = g };

I have to admit I'm always somewhat rusty on join ... into but I think this will do what you're after.


Presuming you do want a left join, as per your question, do:

var query = from pt in model.ProductTypes
            select new
            {
                ProductType = pt,
                Products = from p in pt.Products
                           where p.SeasonId == seasonId
                           select p
            };
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜