views:

70

answers:

1

I have the following table structure, which is imported into an Entity Framework project: (NOTE: I mislabled T1Name as T2Name in Table1)

alt text

I have labeled the Entity Objects. The many-to-many joint table Table5, is represented as an EntityCollection<Entity4> in Entity3, and as an EntityCollection<Entity3> in Entity4 (EntityCollection<T> implements IEnumerable<T>, so it can be queried). I need to construct a result set that is:

T1Name, T2Name, T3Name

This will result in repeat entries for T1Name, and T2Name.

Could someone show me how to write this LINQ query?

Thank you for any help.

+2  A: 
var q = from e3 in Context.Table3
        from e4 in e3.Table4s     // that's your many-to-many
        select new
        {
            Name3 = e3.T3Name,
            Name2 = e4.Table2.T2Name,
            Name1 = e4.Table1.T1Name // presuming Table1.T2Name in your diagram is a typo
        };

"Dot notation":

var q = Context.Table3
               .SelectMany(e3 => e3.Select(e4 => 
                                               new {
                                                   Name3 = e3.T3Name,
                                                   Name2 = e4.Table2.T2Name,
                                                   Name1 = e4.Table1.T1Name
                                               });

Notice I didn't use join at all. That's on purpose; you don't need it here.

Craig Stuntz
Do you know what that would translate into in dot notation?
Sako73
Can you clarify the question, please? I'm not sure what you're asking.
Craig Stuntz
I know that the query notation you used above is translated into the form: List.Where(x => x.????).Select(y => y).etc... I was wondering if you knew how your query translated. Just because I am trying to understand LINQ better. Thank you.
Sako73
Oh, OK. I'll add that.
Craig Stuntz
Thanks Craig. Great answer as usual.
Sako73
By the way, LINQPad will translate any query into this notation for you, and can use your EF model.
Craig Stuntz