5

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

1
  • What do you mean by "But this doesn't seem to take care of ChildCategories??" Commented Jun 14, 2011 at 23:32

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.