I am using asp net core 2.0 and entity framework to access a MySQL database. My model structure looks like
public class Parent
{
[Key]
public int Id { get; set; }
public virtual ICollection<Child> Child { get; set; }
[NotMapped]
public virtual bool HasGrandchild { get; set; }
}
public class Child
{
[Key]
public int Id { get; set; }
public int ParentId { get; set; }
public virtual ICollection<Grandchild> Grandchild { get; set; }
}
public class Grandchild
{
[Key]
public int Id { get; set; }
public int ChildId { get; set; }
}
I want to check whether there are any records of grandchild in the class Parent
. I know I can use Include
and ThenInclude
to retrieve the child and grandchild. However, the Grandchild
is really big. I don't want to return them. Alternatively, I could use for
loop to count the number Grandchild
. For example,
List<Parent> p_list = _context.Parent.ToList();
foreach(Parent p in p_list)
{
List<Child> c_list = _context.Child
.Where(c => c.ParentId == p.Id)
.ToList();
int NumberOfGrandchild = 0;
foreach (Child c in c_list)
{
List<Grandchild> gc_list = _context.Grandchild
.Where(gc =>gc.ChildId == c.Id)
.ToList();
NumberOfGrandchild += gc_list.Count();
}
p.HasGrandchild = false;
if (NumberOfGrandchild > 0) {
p.HasGrandchild = true;
}
}
The performance of this method is very slow, especially for the big table.
Is there any better method to check whether there are any grandchild records.