开发者

Why is ToLookup() dependent on load options in Linq2Sql?

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 opt开发者_StackOverflow中文版ions 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.


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);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜