How To Count Associated Entities using Where In Entity Framework

放肆的年华 提交于 2019-12-06 06:09:34

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();
Felipe Fujiy Pessoto

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!