How to load related data (parent-child-grandchild) in EF code first?

ef-code-first entity-framework entity-framework-4.1 entity-framework-5 entity-framework-6

Question

I've got this thing:

public class DynamicPage {

    public int PageId { get; set; }

    public int Order { get; set; }

    public string MenuText { get; set; }

    public string MenuHover { get; set; }

    public int? ParentId { get; set; }

    public virtual DynamicPage Parent { get; set; }

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

This entity may have three levels: grandparent, kid, and parent. How do I add the Parent (level 1), all connected children (level 2), and, if applicable, all linked grandkids (level 3), to the Parent (level 1)? Thank you for your assistance.

1
7
6/2/2014 2:22:22 AM

Accepted Answer

EF 4.1 syntax and feature:

var entity = context.Parents
    .Include(p => p.Children.Select(c => c.GrandChildren))
    .FirstOrDefault(p => p.Id == 1); // or whatever condition
11
9/22/2011 5:39:49 PM

Popular Answer

If you want to simplify your life, name your table IDs simply according to the EF Code First guidelines.Id (Or you might use name of table PlusId , e.g.,DyanmicPageId ).

You should now have something similar to this:

public class DynamicPage
{
    public int Id { get; set; }
    public int Order { get; set; }
    public string MenuText { get; set; }
    public string MenuHover { get; set; }
    public int? ParentId { get; set; }

    public virtual DynamicPage Parent { get; set; }
    public virtual ICollection<DynamicPage> Children { get; set; }
}

Then, you must clearly establish the link between parents and children in anOnModelCreating approach in yourDbContext class.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<DynamicPage>()
        .HasMany(page => page.Children)
        .WithRequired(child => child.Parent)
        .HasForeignKey(child => child.ParentId);
}

Then, if required, choose from children or grandchildren:

var parent = dbContext.DynamicPages.Where(page => page.ParentId == null);
var children = parent.Children;
var grandchildren = parent.SelectMany(page => page.Children);
var allRelatedPages = parent.Union(children).Union(grandchildren);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow