问题
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.Comments is a ICollection
回答1:
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
回答2:
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();
回答3:
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?
回答4:
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.
来源:https://stackoverflow.com/questions/5024199/how-to-count-associated-entities-using-where-in-entity-framework