Search code examples
c#entity-frameworklinqentity-framework-corelinq-to-entities

How to include 2 parents to a child list in Entity Framework Core?


I have this class and a context class:

public class Parent
{
    public int Id { get; set; }
    public virtual ICollection<Child> Children { get; set; }
}

public class Child
{
    public int Id { get; set; }

    public int ParentId { get; set; }
    public int ForeignId { get; set; }

    [ForeignKey("ParentId")]
    public virtual Parent Parent{ get; set; }
    [ForeignKey("ForeignId")]
    public virtual Foreign Foreign{ get; set; }

    public virtual ICollection<GrandChild> GrandChildren { get; set; }
}

public class GrandChild
{
    public int Id { get; set; }
    public int ChildId { get; set; }

    [ForeignKey("ChildId")]
    public virtual Child Child{ get; set; }
}

public class Foreign
{
    public int Id { get; set; }
    public string name { get; set; }

    public virtual ICollection<Child> Children { get; set; }
}

I want to show a list of Parent with Including their children and granchildren. I want to include Foreign table, too. because I need its fields. I wrote this code:

var list = context.Parents.Include(p => p.Children).ThenInclude(p => p.GrandChildren).Tolist();

How Can I add or include foreign table to this query?

I wrote below code but it had error:

var list = context.Parents
    .Include(p => p.Children)
        .ThenInclude(p => p.GrandChildren)
    .Include(p => p.Children.FirstOrDefault().Foreign).Tolist();

Solution

  • You need to add 2 includes:

     var list = context.Parents
    
                    .Include(p => p.Children)
                    .ThenInclude(c => c.GrandChildren)
                    .Include(p => p.Children)
                    .ThenInclude(c => c.Foreign).ToList();