简体   繁体   English

如何在单个实体框架查询中返回许多子集合Count()

[英]How to return many Child Collections Count() in a single entity framework query

I have two entities, Parent and Child, in Entity Framework. 我在Entity Framework中有两个实体,Parent和Child。

The parent has a collection of Child entities. 父级有一组子实体。

In my query, I want to return only the Parent entities (the fully typed EF types) and also the Count() of the Child entities (this could be set to a property on the Parent), but I only want to do this in one call to the database, without writing a custom S-Proc. 在我的查询中,我想只返回父实体(完全类型的EF类型)以及子实体的Count()(这可以设置为Parent上的属性),但我只想在一次调用数据库,无需编写自定义S-Proc。 Is this possible? 这可能吗?

Essential, I want to turn this into a single query: 基本的,我想把它变成一个单一的查询:

EFContext content = new EFContext();
IQueryable<Parent> parentQuery = context.Parent.Select();
foreach(Parent parent in parentQuery)
{
  parent.NoChildItems = parent.Childs.Count();
}

When I activate the enumerator on this this, it calls the database for the list, and again for each Count() query. 当我在此激活枚举器时,它会调用列表的数据库,并再次为每个Count()查询调用。 I return approx 100 items each time and so would rather not make 100 seperate calls just for the number of child items. 我每次返回大约100个项目,因此不希望仅针对子项目的数量进行100次单独调用。

Thanks for any help. 谢谢你的帮助。

This should work: 这应该工作:

IQueryable parentQuery = context.Parent.Select(p => new { Parent = p, ChildCount = p.Childs.Count() });

EDIT 编辑

If you define: 如果你定义:

public class ParentModel
{
    public Task Parent { get; set; }
    public int ChildCount { get; set; }
}

you can use 您可以使用

IQueryable parentQuery = context.Parent.Select(p => new ParentModel { Parent = p, ChildCount = p.Childs.Count() });

EDIT 编辑

You can also do: 你也可以这样做:

var parentQuery = context.Parent.Select(p => new { Parent = p, ChildCount = p.Childs.Count() }).ToList();
parentQuery.ForEach(p => p.Parent.ChildCount = p.ChildCount);
var result = return parentQuery.Select(p => p.Parent);

Short and you have your property populated. 简短,你已经填充了你的财产。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM