我正在使用以下数据库表创建一个简单的博客系统:
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
};
这会成功返回所有帖子,帖子所属的类别以及帖子作者。我的问题是如何为每个帖子获取所有相关标签。我使用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?
有人可以帮助我指出正确的方向吗?
由于
答案 0 :(得分:1)
您必须加入tags
和posttags
,然后将数据分组到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)
};
答案 1 :(得分:-2)
虽然我不是LinQ的专家,但你需要的是左/右加入。您可以使用DefaultIfEmpty()在LinQ中实现相同的功能。
请查看Entity framework - right join to a view和http://forums.asp.net/t/1728935.aspx?left+right+join+in+linq+or+lambda