我有这个:
var queryResult = (from post in posts
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = post.Comments.Count()
}).ToList();
但我需要这样的事情:
var queryResult = (from post in posts
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = post.Comments.Where(x=>x.IsPublic).Count()
}).ToList();
但是post.Comments是一个ICollection
答案 0 :(得分:0)
如何像这样使用Enumerable.Cast<T>()
?
var queryResult = (from post in posts
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = post.Comments.Cast<Comment>()
.Where(x=>x.IsPublic).Count()
}).ToList();
假设post.Comments
的类型为Comment
答案 1 :(得分:0)
尝试:
var queryResult = (from post in context.Posts
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = context.Comments.Where(c => c.Post == post).Where(c => IsPublic == 1).Count()
}).ToList();
答案 2 :(得分:0)
这有效:
var queryResult = (from post in posts
join comment in comments.Where(x=> x.IsPublic) on post.Id equals comment.Post.Id into g
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = g.Count()
})
但是在所有解决方案中我们都遇到了这个问题How to use Include and Anonymous Type in same query in Entity Framework?
答案 3 :(得分:0)
我是按照LukLed的说法写的,但为了使它能够工作,我将使用Post实体的PK:
var queryResult = (from post in context.Posts
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = context.Comments.Where(c => c.Post.Id == post.Id && c.IsPublic == 1).Count()
}).ToList();
或Post.Id可以写为PostId,如果通过关联公开forign键,我相信它会更有效率。