C# 从联接表获取计数-EFCodeFirst
因此,我最近开始检查ASP.NETMVC3和EFCodeFirst,并陷入困境。 我有两种型号: 人: 和成分:C# 从联接表获取计数-EFCodeFirst,c#,.net,asp.net,linq,asp.net-mvc-3,C#,.net,Asp.net,Linq,Asp.net Mvc 3,因此,我最近开始检查ASP.NETMVC3和EFCodeFirst,并陷入困境。 我有两种型号: 人: 和成分: public class Ingredient { public int IngredientID { get; set; } [Required(ErrorMessage = "Ingredient is a required field")] public string Name { get; set; } public virtual ICo
public class Ingredient {
public int IngredientID { get; set; }
[Required(ErrorMessage = "Ingredient is a required field")]
public string Name { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
您应该将
公共成分IngredientID{get;set;}
标记为虚拟,这样可以延迟加载成分表。你也应该称它为配料,因为它不仅仅是ID,它是一个被引用的实际配料
如果我理解正确,你想知道哪种配料最受欢迎吗?如果是这样,只需按Component.IngCreditId对人员进行分组,并计算每个分组中的人数
另一种方法是添加
publicvirtualicollection Persons{get;set;}
字段设置为配料类,现在您只需执行以下操作即可
var tenMostPopularIngredients = (from i in Ingredients
orderby i.Persons.Count() descending
select i).Take(10);
这将为您提供一个字典,其中每个成分名称作为键,计数作为值,按计数降序排列。如果出现ArgumentException,是因为您有多个同名成分:
var tenMostPopularIngredients = (from i in ingredients
let count = i.Persons.Count()
orderby count descending
select new
{
Ingredient = i,
Count = count
}
).Take(10).ToDictionary(t => t.Ingredient.Name,t => t.Count);
您应该将
公共成分IngredientID{get;set;}
标记为虚拟,这样可以延迟加载成分表。你也应该称它为配料,因为它不仅仅是ID,它是一个被引用的实际配料
如果我理解正确,你想知道哪种配料最受欢迎吗?如果是这样,只需按Component.IngCreditId对人员进行分组,并计算每个分组中的人数
另一种方法是添加
publicvirtualicollection Persons{get;set;}
字段设置为配料类,现在您只需执行以下操作即可
var tenMostPopularIngredients = (from i in Ingredients
orderby i.Persons.Count() descending
select i).Take(10);
这将为您提供一个字典,其中每个成分名称作为键,计数作为值,按计数降序排列。如果出现ArgumentException,是因为您有多个同名成分:
var tenMostPopularIngredients = (from i in ingredients
let count = i.Persons.Count()
orderby count descending
select new
{
Ingredient = i,
Count = count
}
).Take(10).ToDictionary(t => t.Ingredient.Name,t => t.Count);
和的组合是不够的?和的组合是不够的?+1我没有注意到他没有熟练地从一种成分导航到另一种成分。说得太快了,显然它有点奏效,但只是给了我一张每种成分的列表,上面都有重复的成分。Ie:-番茄-沙拉-苹果-番茄你确定没有重复的配料吗?试试我刚才在回答中添加的内容。你是对的,我有重复的成分。我不知道该怎么解决,所以我提出了一个新问题+1我没注意到他没有快速地从一种成分导航到另一种成分。说得太快了,显然它有点奏效,但只是给了我一份含有重复成分的每种成分的列表。Ie:-番茄-沙拉-苹果-番茄你确定没有重复的配料吗?试试我刚才在回答中添加的内容。你是对的,我有重复的成分。不知道如何解决它,所以我提出了一个新问题