views:

65

answers:

2

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-one -> 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!

+4  A: 

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.

Jon Skeet
It works! thank you! But do you know if its something that i should put im my repository or if its something that should be in the controller? If its in the repository, i will have to make a new object to be return. Im not sure that its a good way of doing this!
Alexandre Jobin
@Alexandre: I really don't know, to be honest.
Jon Skeet
i have decided to put it in the Controller since that its specific for the View. And its must easier!
Alexandre Jobin
This is an inner join, not a left join.
Craig Stuntz
@Craig: Using "join into" rather than just "join" performs a group join, which includes empty right sequences when the left element doesn't match anything.
Jon Skeet
My mistake; I missed `into`.
Craig Stuntz
+2  A: 

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
            };
Craig Stuntz
its more readable that way. But i don't understand why Jon's version worked too even if it was an inner join. Thank you very much!
Alexandre Jobin
Inner join works fine as long as the data happens to be on both sides.
Craig Stuntz
the weird thing is that i had a few ProductTypes without any Products and everything was fine. Anyway, everything works great with your solution :)
Alexandre Jobin
@Craig: No, mine was *not* an inner join. If you look at the compiled code, it would use `Queryable.GroupJoin`, which is the closest LINQ has to a true left join. (It's often combined with `DefaultIfEmpty` to end up with a null value in the right side, but there's no need for it in this case.)
Jon Skeet