Count child matches in linq Entity Framework
I try to count the number of child elements for each parent where the parent id is in a list if ints. But the count is not correct. Is it not possible to make a query like this? What is the correct way of doing this?
List<int> ids = [1, 2, 3];
var counts = (from d in db.Parent where ids.Contains(d.Id) select d.Child.Count()).ToList();
Assuming Child is a collection, because you are attempting to count it. Try the following: var counts = db.Parent.Where(x => ids.Contains(x.Id)).SelectMany(x => x.Child).Count();
"Count" will work on an IEnumerable. However it seems you are trying to work with a collection of IEnumerables. In these situations use "SelectMany" so that all the resulting collections are joined into one single collection.
The query does exact what I want, sorry for that. My problem was that the ids list was not sorted and that somehow made the query to not sort the output as the ids list was sorted. By sort the ids list (ids.Orderby(id)) this question was solved.
一个计数列表并没有别的可能提供足够的信息,但通常关于包含实体的一些信息将是有用的(如果只是为了防止混淆):
List<int> ids = [1, 2, 3];
var counts = (from d in db.Parent where ids.Contains(d.Id)
select new
{
Parent = d.Name,
ChildCount = d.Child.Count()
}).ToList();
链接地址: http://www.djcxy.com/p/37662.html
上一篇: 使用自定义排序顺序对对象的ArrayList进行排序
下一篇: 在linq实体框架中计数孩子匹配