如何显示一对多关系表中的记录?

时间:2017-02-27 22:59:16

标签: asp.net linq-to-sql ef-code-first

[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; }
}

以上是两个表格,我想显示类别列表,包括每个类别中的产品数量。我该如何使用它?

2 个答案:

答案 0 :(得分:1)

令人惊讶的是,在重复的问题+答案和这里给出的答案中,对于任何你可以做的事情都没有发生:

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

答案 1 :(得分:-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