我试图显示博客帖子列表,所有博客帖子都由特定作者归档到特定类别,并且可以包含x个标签。这是我的数据库设置:
Posts
PostId
Title
PostDate
Body
Draft
Categories
CategoryId
CategoryName
PostCategories
PostId
CategoryId
Authors
AuthorId
AuthorName
PostAuthors
AuthorId
PostId
Tags
TagId
TagName
PostTags
PostId
TagId
示例数据(用于分隔数据库列的逗号):
Posts
-----
1, Test Post #1, 2/5/2015 12:00:00, This is a test post, 0
2, Test Post #2, 2/5/2015 12:00:00, This is another test post, 0
Categories
----------
1 Test Posts
PostCategories
--------------
1, 1
2, 1
Authors
-------
1, Test Author
PostAuthors
-----------
1, 1
2, 1
Tags
----
1, C#
2, ASP.NET MVC
3, LINQ
PostTags
--------
1, 1
1, 2
1, 3
2, 1
2, 2
我使用实体框架基于数据库表创建模型并创建了一个视图模型BlogViewModel
:
public class BlogViewModel {
public Post Post { get; set; }
public Category Category { get; set; }
public Author Author { get; set; }
public IEnumerable<Tag> Tags { get; set; }
}
我有以下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
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.FirstOrDefault().p,
Category = g.FirstOrDefault().c,
Author = g.FirstOrDefault().a,
Tags = g.Select(x=>x.t)
};
如果有一种更简洁的方法来获取所有这些数据而没有所有连接,我当然会对此持开放态度。
有人能看出为什么会这样,并帮助我指出正确的方向吗?