c# - Linq 中的计算字段按总和分组

标签 c# postgresql entity-framework linq

我想为表之间的三向连接创建一个计算字段。这三个表分别命名为 Recipes、Ingredients 和 IngredientsToRecipes。这些表携带的值如下:

食谱

  • 配方ID
  • 用户ID
  • 姓名
  • 描述

成分

  • 姓名
  • 价格
  • 描述

成分到食谱

  • 配方ID

现在,我开始进行三向连接,然后按菜谱分组,因为连接中会有很多重复项,我是这样做的:

var recipesJoin = (
    from a in db.IngredientsToRecipes
    join b in db.Recipes on a.recipeID equals b.recipeID
    join c in db.Ingredients on a.siin equals c.siin
    select new
    {
        recipeID = a.recipeID,
        userID = b.userID,
        name = b.name,
        description = b.description,
        price = c.price
    }).GroupBy(x=>x.recipeID);

然后我的计划是从 recipesJoin 创建一个新表,我将在其中对价格求和,然后只返回价格低于变量 y 的行。我已经尝试了很多东西,但我对 Linq 的理解是从今天开始的,所以我的理解非常有限。 我试过了

var recipesJoin = (
    from a in db.IngredientsToRecipes
    join b in db.Recipes on a.recipeID equals b.recipeID
    join c in db.Ingredients on a.siin equals c.siin
    select new
    {
        recipeID = a.recipeID,
        userID = b.userID,
        name = b.name,
        description = b.description,
        price = c.price
    }).GroupBy(x=>x.recipeID).Sum(y=>y.price);

但是我得到了错误:

Severity Code Description Project File Line Suppression State Error CS1061 'IGrouping>' does not contain a definition for 'price' and no extension method 'price' accepting a first argument of type 'IGrouping>' could be found (are you missing a using directive or an assembly reference?) SalWebAPI C:\Users\Samuel.endeva\source\repos\SalApp\SalApp\SalWebAPI\Controllers\RecipeTypeBudgetController.cs 31 Active

我不太明白这个错误。我的主要目标是求和并分组到一个计算字段中,删除高于特定价格的行,然后将新表与另一个表连接起来进行简单检查。我如何计算这样的 3 路连接的总和?

最佳答案

您应该选择分组操作后的结果。由于您按 recipeID 分组,我相信您需要每个唯一食谱 ID 的总价,因此这里是建议:

var recipesJoin = (
      from a in db.IngredientsToRecipes
      join b in db.Recipes on a.recipeID equals b.recipeID
      join c in db.Ingredients on a.siin equals c.siin
      select new
      {
          recipeID = a.recipeID,
          userID = b.userID,
          name = b.name,
          description = b.description,
          price = c.price
      }).GroupBy(x => x.recipeID) // 1
          .Select(grp=> new //2
          {
              recipeID = grp.Key,
              name= grp.First().name, // same ID => same name anyway
              toalPrice = grp.Sum(b => b.price) //3
          })
          .Where(y => y.totalPrice < 2000); //4

1- 按食谱 ID 分组

2- 选择结果以获得每个唯一配方 ID 的不同实体

3- 在这里您可以对每个唯一的 recipeID 求和(通过 y.Key==grouping key 获得)

4- 过滤结果(将 2000 替换为您的实际阈值)

关于c# - Linq 中的计算字段按总和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49452640/

相关文章:

c# - EF 4 在列类型为 varchar 的 SQL 中生成 UNICODE 字符串常量。如何避免?

sql - 将原始 SQL 结果映射到 .NET Core 中的对象列表

c# - 在 MVVM Light 5.2.0.37222 中找不到 GalaSoft.MvvmLight.CommandWpf 命名空间

c# - 如何获得子集的所有可能组合?

C# 返回一个枚举和一个 int 数组

java - 在一个事务中组合 JPA 和 JDBC 操作

c# - 复杂的orderby问题( Entity Framework )

c# - NHibernate回滚似乎不起作用

sql - Perl/Postgresql : plperl. 所以 undefined symbol :Perl_sv_2bool_flags

json - Postgresql - 在从 JSON 和表中选择值时插入到两个表中