有两张桌子。一个用于Fruit
,另一个用于FruitBag
。可能有许多FruitBag
包含许多Fruit
。我希望能够计算出特定水果袋内相同水果的数量。
public ActionResult FruitCheck(int fruitBagId, int fruitId)
{
var getFruitBag = db.FruitBags.SingleOrDefault(fb => fb.Id == fruitBagId);
int Amount = getFruitBag.// check amount same fruit-id inside current FruitBag
....
}
以下代码不起作用,但它是关于我的想法,所以你明白我的意思:
int Amount = getFruitBag.Count(c=> c.Fruit.Where(f=> f.Id == fruitId))
public partial class FruitBag {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public FruitBag() {
this.Fruits = new HashSet<Fruit>();
}
public System.Guid Id { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Fruit> Fruits { get; set; }
}
public partial class Fruit {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Fruit() {
this.FruitBags = new HashSet<FruitBag>();
}
public System.Guid ID { get; set; }
public string Type { get; set; }
public int Price { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<FruitBag> FruitBags { get; set; }
}
答案 0 :(得分:0)
试试这个:
var amount = getFruitBag.Fruit.
GroupBy(x => x.Id).
Select(x => new { x.Key, Value = x.Count() }).ToList();
您将获得一个匿名类型,其中包含所有水果及其数量。