简体   繁体   English

实体框架:多对多的计数和总和

[英]Entity Framework: Many To Many Count and Sum

I am using the Entity Framework. 我正在使用实体框架。 I have a many to many relationship Articles <-> Categories. 我有很多对很多关系文章<->类别。 Each article can belong to many categories, and each category can belong to more than one article. 每个文章可以属于多个类别,并且每个类别可以属于一个以上的文章。 I can get the COUNT of articles within each category: 我可以获得每个类别中的COUNT条文章:

public IEnumerable<MenuCategory> GetMenuCategories()
{
   return (from c in db.CategorySet.Include("Articles")
     orderby c.CategoryName
     select new MenuCategory
     {
        CategoryID = c.CategoryID,
        CategoryName = c.CategoryName,
        CountOfCategory = c.Articles.Count()
      });

}

But I also need to get the total number of articles so that I can calculate what percentage of articles is in each category. 但是我还需要获取文章总数,以便可以计算每个类别中文章的百分比。 Can anyone tell me how to do that by extending the code above and without making a separate call to the database? 谁能告诉我如何通过扩展上面的代码而不用单独调用数据库来做到这一点?

Thanks 谢谢

The code needs to know the total number of articles in order to do this. 为此,代码需要知道文章的总数。

If you want to avoid a second database call then you can do the calc in the database and return it as an extra column in the result set. 如果要避免再次调用数据库,则可以在数据库中进行计算,并将其作为结果集中的额外列返回。 There are different ways to acheive this but one would be to use a view and have a SQL function TotalArticles, then your calc is just articleCount / TotalArticles. 有多种方法可以实现此目的,但一种方法是使用视图并具有SQL函数TotalArticles,那么您的计算结果就是articleCount / TotalArticles。 I don't know much about the entity-framework so I'm not sure if this is workable. 我对实体框架了解不多,所以不确定这是否可行。

If you can't do the calc in the database then I imagine the second database call is unavoidable although it is just a count of articles so hardly adding much overhead. 如果您无法在数据库中进行计算,那么我想第二次数据库调用是不可避免的,尽管这只是文章的数目,因此几乎不会增加太多开销。 You could make this call before the main call and then add the value to your results in a similar manner to above, ie PercentageOfArticles = c.Articles.Count() / articleCount 您可以在主调用之前进行此调用,然后以与上述类似的方式将值添加到结果中,即PercentageOfArticles = c.Articles.Count() / articleCount

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

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