I am using C#, ASP.Net, Entity Framework, LINQ, Microsoft SQLServer
I have two tables
tblCategories
Id
Name
ParentId (parentId is the Id of another category in this table that is the parent of this one)
tblQuestion
Id
CategoryId
Etc.
So say my categories table contains
Programming (Id 1 ParentId null) - directly contains 10 questions
C# (Id 25 ParentId 1) – directly contains 5 questions
Interview Questions (Id 99 ParentId 25) - directly contains 2 questions
Variables (Id 100 ParentId 25) – directly contains 1 question Networking (Id 2 Parent Id null)
I want to know how many questions exist for a each category, including its child categories.
In other words in this example 18 questions are in programming, 8 are in C#
Is it possible to do this in a query or do I need some kind of iterative loop called on each category? such as db.categories.Where(something).count()
Here is my category class:
public class Category
{
[Key]
public int Id { get; set; }
[StringLength(40)]
public string Name { get; set; }
public int? ParentId { get; set; }
[JsonIgnore]
public virtual ICollection<Category> Children { get; set; }
[JsonIgnore]
public virtual Category Parent { get; set; }
[JsonIgnore]
public virtual ICollection<Question> Questions { get; set; }
}
then in OnModelCreating:
modelBuilder.Entity<Category>()
.HasMany(x => x.Children)
.WithOptional(y => y.Parent)
.HasForeignKey(z => z.ParentId)
.WillCascadeOnDelete(false);
there are several similar questions on StackOverflow, like this: Help with generating a report from data in a parent-children model and this linq aggregated nested count but I can't find one that is a good enough match and I can understand
To clarify, I want to know the number of questions in the child categories, not the number of child categories.