我想为表之间的三向连接创建一个计算字段。这三个表名为Recipes,Ingredients和IngredientsToRecipes。这些表携带的值如下:
食谱
成分</ P>
IngredientsToRecipes
现在,我开始做一个三向连接,然后按照配方进行分组,因为连接会有很多重复,这就是我这样做的方法:
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);
但是我收到了错误:
严重级代码描述项目文件行抑制状态 错误CS1061&#39; IGrouping&gt;&#39;不包含&#39; price&#39;的定义没有延期的方法&#39;价格&#39;接受类型&#39; IGrouping&gt;&#39;的第一个参数。可以找到(你错过了使用指令或程序集引用吗?)SalWebAPI C:\ Users \ Samuel.endeva \ source \ repos \ SalApp \ SalApp \ SalWebAPI \ Controllers \ RecipeTypeBudgetController.cs 31 Active
我不太明白错误。我的主要目标是对计算字段求和并分组,删除超过特定价格的行,然后将该新表与另一个表连接以进行简单检查。如何为这样的3方式连接做总结?
答案 0 :(得分:2)
您应该在分组操作后选择结果。由于您按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- group by recipedID
2-选择结果以获取每个唯一配方ID的不同实体
3-在这里你可以为每个唯一的recipeID(通过y.Key ==分组键获得)得到总和
4-过滤结果(用真实阈值替换2000)