views:

88

answers:

1

Lets say I have 3 tables Posts, PostTags and Tags defining a many-to-many relationship. I want to get a lookup table that will give me all the Posts related to a given tag so I use the following code:

return dataContext.PostTags.ToLookup(pt => pt.Tag, pt => pt.Post);

In unit test all went fine but in the real application, it didn't work. I found out that I had different load options between my unit test and my application.

When dataContext.DeferredLoadingEnabled = true;, everything is fine and works as expected but when dataContext.DeferredLoadingEnabled = false; and you don't have the load options from PostTags to Post and Tag, the lookup returned contains a single key (null) with an empty array for value. The generated SQL is

SELECT [t0].[PostID], [t0].[TagID]
FROM [dbo].[PostTags] AS [t0]

So when it generates the lookup, pt => pt.Post returns null and the same goes for Tags.

Why can't the Linq2SQL provider generate the right SQL in that case?

Clarification: By the right SQL, any SQL that would return the right Post and Tag objects and allow for grouping them correctly.

+1  A: 

I found a way to make it work no matter what the DeferredLoadingEnabled property value is and whatever the loadoptions are:

var lookup = (from pt in dataContext.PostTags
              select new {pt.Post, pt.Tag}).ToLookup(x => x.Tag, x => x.Post);
Marcel Gosselin
Microsoft's team seems to think this is the desired behaviour: http://social.msdn.microsoft.com/Forums/en-CA/netfxbcl/thread/b3c13f39-6173-4348-9036-76e8a57a6f4a Accepted my own answer with workaround.
Marcel Gosselin