Linq查询,选择内部查询到列表?

时间:2010-10-17 07:11:09

标签: asp.net linq linq-to-sql

我正在写一个linq查询来选择一个博客帖子,

    from data in dataContext.Blog_BlogPosts
        join tagsData in dataContext.Blog_TagToPostConnections on data.BlogPostID equals tagsData.BlogPostID
        where data.Slug == "asp-programmering"
        select new BlogPost
        {
            Title = data.Title,
            Slug = data.Slug,
            Author = data.Author,
            Text = data.Text,
            Tags = (from tags in dataContext.Blog_Tags where tags.TagID == tagsData.TagID select new Tag { TagID = tags.TagID, TagName = tags.Tag }).ToList()
        };

blogpost类看起来像这样(用于测试)

    public class BlogPost
    {
        public string Slug { get; set; }
        public string Title { get; set; }
        public string Text { get; set; }
        public string Author { get; set; }
        public DateTime Published { get; set; }
        public List<Tag> Tags { get; set; }
    }

我测试的博客帖子附有3个标签。表结构是:

(表)BlogPost - &gt; (表)BlogPostTags&lt; - (表)标签

所以BlogPostTags表只包含2个字段,BlogPostID和TagID。

当我运行上面的查询时,我得到3个结果。相同的博客帖子3次,但每个都有1个标签。它应该返回1个帖子,带有3个标签。问题出在上面的标签查询中。

1 个答案:

答案 0 :(得分:3)

这是因为你在外表达式中加入了Blog_TagToPostConnections。由于有三个匹配的标记,因此连接将生成三个结果项。将联接移动到分配给Tags的表达式(这是您想要要弹出的三件事)。

from data in dataContext.Blog_BlogPosts
    where data.Slug == "asp-programmering"
    select new BlogPost
    {
        Title = data.Title,
        Slug = data.Slug,
        Author = data.Author,
        Text = data.Text,
        Tags = (from tags in dataContext.Blog_Tags
                join tagsData in dataContext.Blog_TagToPostConnections
                     on tags.TagID equals tagsData.TagID
                where data.BlogPostID == tagsData.BlogPostID
                select new Tag { TagID = tags.TagID, TagName = tags.Tag }
               ).ToList()
    };