[英]Get Count of Lazy Loaded Child Collection Using LINQ and Entity Framework
I have a class such as: 我有一个像这样的课程:
public class Category
{
public int CategoryId { get; set; }
[Required]
public string Name { get; set; }
[NotMapped]
public int ProductCount { get; set; }
public virtual IEnumerable<Product> Products { get; set; }
}
I have a query that currently looks like this: 我有一个查询,当前看起来像这样:
context.Categories.SortBy(sortByExpression).Skip(startRowIndex).Take(maximumRows)
I need to include the ProductCount field in my category grid. 我需要在类别网格中包含ProductCount字段。 Is it possible to extend this LINQ query to give me the ProductCount property without reading in the entire Product collection? 是否可以扩展此LINQ查询以提供给我ProductCount属性,而无需阅读整个Product集合? I can do this in a sub query using good old SQL, but I am stumped using LINQ. 我可以在使用良好的旧SQL的子查询中执行此操作,但是我却无法使用LINQ。
Thanks 谢谢
Is this roughly what you are looking for: 这大致就是您要寻找的内容:
context.Categories.SortBy(sortByExpression).Skip(startRowIndex).Take(maximumRows)
.Select(c => new { c.CategoryId, c.Name, ProductCount = c.Products.Count() });
or have I misunderstood your question? 还是我误解了你的问题?
updated the code 更新了代码
Your question is not clear as enough but if I understood well you want the new column in result for example productCount and you did it with SQL query like below: 您的问题还不够清楚,但是如果我理解得很好,那么您想在结果中添加新列,例如productCount,并使用如下所示的SQL查询来完成:
SELECT c.*, , (SELECT COUNT(*) FROM Products p WHERE p.categoryId = c.id) AS productCount FROM
Categories c
WHERE <Conditions>
Now you want to be able do that using linq(If your question really this), you can do it as below: 现在,您希望能够使用linq来做到这一点(如果您的问题确实如此),则可以按照以下步骤进行操作:
List<Category> categoryList = (from c in context.Categories let pCount = c.Products.Count() select
new { categoryId = c.CategoryId, CategoryName = c.Name, productCount = pCount})
.OrderBy([sortByExpression]).Skip([startRowIndex]).Take([maximumRows]).ToList();
Hope this help. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.