如何使用entity framework中的位置计算关联实体

我有这个:

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

如何像这样使用Enumerable.Cast()

 var queryResult = (from post in posts select new { post, post.Author, post.Tags, post.Categories, Count = post.Comments.Cast() .Where(x=>x.IsPublic).Count() }).ToList(); 

假设post.CommentsComment类型

尝试:

 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(); 

这有效:

  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() }) 

但是在所有解决方案中我们都有这个问题如何在Entity Framework中的同一查询中使用Include和Anonymous Type?

我把它写成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键,我相信它会更有效率。