2017-02-27 199 views
0
[Table("Categories")] 
public class Category 
{ 
    public Category() 
    {  
     Products = new HashSet<Product>(); 
    } 
    public int CategoryId { get; set; } 
    public string CategoryName { get; set; } 
    public virtual ICollection<Product> Products { get; set; } 
} 

[Table("Product")] 
public class Product 
{  
    public int ProductId { get; set; } 
    [Required, Display(Name = "Product Name")] 
    public string ProductName { get; set; } 
    public DateTime Created { get; set; } 
    public int CategoryId { get; set; } 
    public virtual Category Categories { get; set; } 
} 

以上是兩個表格,我想要顯示類別列表,包括每個類別中產品的數量。我如何使用它?如何顯示一個到多個關係表中的記錄?

+0

歡迎太(因此) 。請閱讀[問]並考慮擴展您的問題以解釋*您想如何使用它*以及您到目前爲止所嘗試的內容,例如 - 您是否需要查詢數據庫?你試過什麼Linq-SQL不起作用? –

+0

此問題已在[這裏]回答(http://stackoverflow.com/questions/3600940/what-linq-query-can-i-use-to-return-a-count-of-all-products-by-類別) –

回答

-1
var categoryCounts = 
    from p in products 
    group p by p.Category into g 
    select new { Category = g.Key, ProductCount = g.Count() }; 

Count of all products by category

+0

所以你的問題不是多對多的。它是一對多的,因爲Categories Table具有產品的ICollection,而您的產品表只有Categories表的外鍵。 –

+0

好吧,我讀得太快了,被複雜的「類別」所迷惑(爲什麼人們會這麼做?)。無論如何,它仍然沒有必要使用分組。您可以簡單地計算每個類別的產品。 –

1

出人意料的是,在重複的問題+答案,這裏給出的答案,也沒有發生任何人,你可以簡單地做:

var counts = from c in context.Categories 
      select new 
      { 
       c.CategoryName, 
       ProductCount = c.Products.Count() 
      }; 
+0

和往常一樣,複雜性被誤認爲是熟練程度。 –

相關問題