linq查询内连接和左连接的问题

时间:2011-03-25 16:21:24

标签: linq entity-framework linq-to-entities

我有3个名为PostsTagsPostXTags的表,PostXTags是帖子和标签之间的连接器。

我尝试在linq中进行以下查询但是我从未实现过理想的结果。

请帮我写一下这个查询的正确linq:

SELECT * FROM Posts
INNER JOIN PostXTags
ON Posts.PostID = PostXTags.PostID
LEFT JOIN Tags
ON PostXTags.TagID = Tags.TagID

2 个答案:

答案 0 :(得分:0)

var query = from p in Posts
            join x in PostXTags on p.PostID equals x.PostID
            join t in Tags on x.TagID equals t.TagID into joinedTags
            from t in joinedTags.DefaultIfEmpty()  //left join                
            select new { Posts = p, Tags = t };    //t could be null   

答案 1 :(得分:0)

我想你想实现这个目标:

var query = context.Tags.Where(t => t.Id == id).SelectMany(t => t.Posts);