How To Count Associated Entities using Where In Entity Framework
I have this:
var queryResult = (from post in posts
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = post.Comments.Count()
}).ToList();
But I need something like this:
var queryResult = (from post in posts
select new
{
post,
post.Author,
post.Tags,
post.Categories,
Count = post.Comments.Where(x=>x.IsPublic).Count()
}).ToList();
But post.开发者_JAVA百科Comments is a ICollection
How about using Enumerable.Cast<T>()
like this ?
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();
assuming post.Comments
is of type Comment
Try:
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();
This works:
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()
})
But in all solutions we have this problem How to use Include and Anonymous Type in same query in Entity Framework?
I'd written it as LukLed did but to make it work I'll use the PK of Post entity:
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();
Or Post.Id could just be written as PostId if forign keys are exposed through the association which I believe it would be more efficient.
精彩评论