2

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.

4

1 に答える 1

1

DeferredLoadingEnabled プロパティの値が何であっても、loadoptions が何であっても、それを機能させる方法を見つけました。

var lookup = (from pt in dataContext.PostTags
              select new {pt.Post, pt.Tag}).ToLookup(x => x.Tag, x => x.Post);
于 2009-11-12T19:44:00.590 に答える