Mapping for self referencing entity in EF Code First

百般思念 提交于 2019-12-04 06:35:46

your POCO class should look like this ...

public class Category
{
   public long Id { get; private set; }
   public string CategoryName { get; private set; }
   public long? ParentCategoryId { get; private set; }
   public virtual Category ParentCategory { get; private set; }       
   public virtual ICollection<Category> SubCategories { get; private set; }
}

public class CategoryConfiguration : EntityTypeConfiguration<Category>
{
    public CategoryConfiguration()
    {
        this.HasKey(x => x.Id);

        this.HasMany(category => category.SubCategories)
            .WithOptional(category => category.ParentCategoryId)
            .HasForeignKey(course => course.UserId)
            .WillCascadeOnDelete(false);
    }
}

Entity Framework 6 handles this. You have to just ensure [Key] annotation is used to identify primary key. Not sure if it works with virtual keyword or not.

 public class Category
{
   [Key]
   public long Id { get; private set; }
   public string CategoryName { get; private set; }
   public long? ParentCategoryId { get; private set; }
   public Category ParentCategory { get; private set; }       
   public ICollection<Category> SubCategories { get; private set; }
}

I think I found it, I added the following in the OnModelCreating operation:

 modelBuilder.Entity<Domain.Entities.Category>().HasOptional<Category>(c => c.ParentCategory).WithMany().Map(m => m.MapKey(new string[] { "Id", "ParentCategoryId" }));

and now the ParentCategory and SubCategories properties work (and I could remove Category1 and Category2). Don't know exactly why SubCategories works though...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!