Lamda按类别和子类别计算总记录

时间:2017-10-25 11:25:09

标签: c# linq entity-framework-6

我有两个实体

分类

public class Category
{
  public int Id {get; set;}
  public int? ParentId {get; set;}
  public string Name {get; set;}
  public virtual ICollection<Document> Documents {get; set;}
}

文档

    public class Document
    {
      public int Id {get; set;}
      public int CategoryId {get; set;}
      public string Name {get; set;}
      public virtual Category Category {get; set;}
    }

如何通过categoryId获取所有子类别的总文档?

示例

分类

Id  ParentId  Name

1   null      One
2   null      Two
3   1         One Live 1
4   3         One Live 2

文档

Id  CategoryId  Name

1   1         Document 1
2   2         Document 5
3   3         Document 2
4   4         Document 3

我想要获得总文件 One 。我应该得到总数3

2 个答案:

答案 0 :(得分:0)

这应该有效

count = (from document in Documents
         join category in Categories 
         on document.CategoryId equals category.Id
         select document).Count();

答案 1 :(得分:-1)

var count= (from c in this.db.categories
             join d in this.db.documents on c.id equals d.CategoryId
             select d).Count();