Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping child items of same class with Entity Framework Code First

I'm trying to map a fairly "standard" category model using EF Code First

public class Category
{
    public int ID { get; set; }
    public int ParentID { get; set; }

    public string Name { get; set; }

    public Category ParentCategory { get; set; }
    public List<Category> ChildCategories { get; set; }
}

I've got something along the lines of:

modelBuilder.Entity<Category>()
    .HasOptional(t => t.ParentCategory)
    .WithMany()
    .HasForeignKey(t => t.ParentCategoryID)
    .WillCascadeOnDelete();

But this doesn't seem to take care of ChildCategories??

Am I missing something?

To avoid the duplicate question argument, I followed the following, however didn't quite answer my specific query:

Code First Mapping for Entity Framework Hierarchy

Entity Framework CTP5 Code-First Mapping - Foreign Key in same table

like image 499
Alex Avatar asked Oct 24 '22 08:10

Alex


1 Answers

Change your Entity to

public class Category
{
    public int ID { get; set; }
    public int? ParentID { get; set; }

    public string Name { get; set; }

    public virtual Category ParentCategory { get; set; }
    public virtual IList<Category> ChildCategories { get; set; }
}

Make ParentID nullable and to allow ChildCategories to be lazy loaded, make it virtual.

like image 78
Eranga Avatar answered Nov 02 '22 12:11

Eranga