Home > Enterprise >  How to define foreign Key in Entity Framework Core
How to define foreign Key in Entity Framework Core

Time:09-17

I am trying to achieve the below table structure, but I am getting error "cannot be used as a property on entity type because it is configured as a navigation."

Can anyone help me.

Category:

Id Name
1 cat1
2 cat2
3 cat3
4 cat4

Sub Category:

Id Category Id Name
1 1 Subcat1
2 1 Subcat2
3 1 Subcat3
1 2 Subcat4
1 3 Subcat5
2 3 Subcat6

Item:

Id CategoryId SubCategoryId Name
1 1 2 item1
2 3 2 item2
3 1 null item3
4 4 null item4
public class Category
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<HrCodeSubType> SubCategories { get; set; }

}

public class SubCategory
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Category")]
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }

    [Required]
    public string Name { get; set; }
}

public class Item
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    [ForeignKey("Category")]
    public int CategoryId { get; set; }
    public virtual Category Category{ get; set; }


    public int? SubCategoryId { get; set; }
    public virtual SubCategory SubCategory { get; set; }
  }

Fluent Api

builder.Entity<Item>().HasOne(x => x.SubCategory)
         .WithMany().HasForeignKey(x => new { x.CategoyId, x.SubCategoyId });

CodePudding user response:

leave only subcategory in the item class since it depends on category already and has one to one relation

public class Item
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    
    public int? SubCategoryId { get; set; }
    public virtual SubCategory SubCategory { get; set; }
  }

and if you use net core 5 you don't need any fluent apis, just add navigaion property to subcategory

public class SubCategory
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Category")]
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }

    [Required]
    public string Name { get; set; }

   public virtual ICollection<Item> Items{ get; set; }

}

public class Category
{
    [Key]
    public int Id { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<SubCategory> SubCategories { get; set; }

}
  • Related