获取找到匹配项的所有行

Get all rows where a match is found

我正在使用以下数据库表创建一个简单的博客系统:

Posts
    PostId
    Title
    PostDate
    Body
    Draft

Categories
    CategoryId
    CategoryName

PostCategories
    PostId
    CategoryId

Authors
    AuthorId
    AuthorName

PostAuthors
    AuthorId
    PostId

Tags
    TagId
    TagName

PostTags
    PostId
    TagId

这是我目前的查询(使用 LINQ):

 var results = from p in posts 
               join pc in postcategories on p.PostId equals pc.PostId 
               join c in categories on pc.PostId equals c.CategoryId 
               join a in authors on pc.PostId equals a.AuthorId 
               select new BlogViewModel { 
                                          Post = p, 
                                          Category = c, 
                                          Author = a 
                                        };

这成功 returns 所有 post,post 所属的类别,以及 post 作者。我的问题是如何获取每个 post 的所有关联标签。我使用 Entity Framework 生成模型并且 BlogViewModel 包含:

public Post Post { get; set; }
public Category Category { get; set; }
public Author Author { get; set; }
public IEnumerable<Tag> Tags { get; set; }

我的直觉告诉我,我需要在 select new BlogViewModel 语句中进行新查询,例如:

... Tags = //new LINQ statement?

有人可以帮我指明正确的方向吗?

谢谢

虽然我不是LinQ专家,但你需要的是Left / Right join。您可以使用 DefaultIfEmpty() 在 LinQ 中实现相同的目的。

请看Entity framework - right join to a view and http://forums.asp.net/t/1728935.aspx?left+right+join+in+linq+or+lambda

您必须加入 tagsposttags,然后在 PostId 上分组数据:

var results = from p in posts
              join pc in postcategories on p.PostId equals pc.PostId
              join c in categories on pc.PostId equals c.CategoryId
              join ap in authorposts on pc.PostId equals ap.PostId
              join a in authors on ap.AuthorId equals a.AuthorId
              join tp in tagposts on p.PostId equals tp.PostId
              join t in tags on tp.TagId equals t.TagId
              group new { t, p, c, a } by tp.PostId into g

              select new BlogViewModel
                        {
                          Post = g.First().p,
                          Category = g.First().c,
                          Author = g.First().a,
                          Tags = g.Select(x=>x.t)
                        };

working fiddle example