Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping for self referencing entity in EF Code First

In my database I have a table Category, with columns Id, CategoryName, ParentCategoryId, where ParentCategoryId has a constraint on Category.Id.

I'm using entity framework code first, where the entity looks like:

public class Category
{
   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 virtual ICollection<Category> SubCategories { get; private set; }
}

If I try to run a query against this, I get the exception:

 The relationship 'ComplaintModel.FK_Complaint_Category' was not loaded because the type 'ComplaintModel.Category' is not available.\r\nThe following information may be useful in resolving the previous error:\r\nThe required property 'Category1' does not exist on the type 'EC.Complaint.Services.Command.Domain.Entities.Category'.\r\n\r\n"}    System.Exception {System.Data.MetadataException}

So it seems it needs navigation properties, if I add these:

 public ICollection<Category> Category1 { get; private set; }
 public long? Category2Id { get; private set; }
 public Category Category2 { get; private set; }

the query works.

But of course, I don't want the Category1 and Category2 properties, I want ParentCategory and SubCategories properties being used.

How can I tell code first to use the correct navigation properties?

like image 948
L-Four Avatar asked Mar 13 '12 12:03

L-Four


2 Answers

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);
    }
}
like image 129
bdparrish Avatar answered Nov 06 '22 02:11

bdparrish


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; }
}
like image 39
amarnath chatterjee Avatar answered Nov 06 '22 00:11

amarnath chatterjee