如何使用实体框架中的实体计数关联实体 [英] How To Count Associated Entities using Where In Entity Framework

查看:95
本文介绍了如何使用实体框架中的实体计数关联实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

        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

But post.Comments is a ICollection

推荐答案

这样做:

        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类型同一个查询?

But in all solutions we have this problem How to use Include and Anonymous Type in same query in Entity Framework?

这篇关于如何使用实体框架中的实体计数关联实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆