How do I configure a navigation property to the same table in Entity Framework?
Asked Answered
R

1

1

How do I configure Entity Framework using fluent configuration to behave the same way that I would do this with attributes:

public class Product
{
    public int? ParentId { get; set; }
    [ForeignKey("ParentId")]
    public virtual Product Parent { get; set; }
}
Rondo answered 15/1, 2015 at 17:8 Comment(0)
C
3

Supposing that you want to create a self referencing entity, I assume that you have a Product class like this:

public class Product
{
    public int Id { get; set; }

    public int? ParentId { get; set; }

    public virtual Product Parent { get; set; }
}

In the context, you need to implement the OnModelCreating method in order to configure the self reference.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Product>().
       HasOptional(e => e.Parent).
       WithMany().
       HasForeignKey(m => m.ParentId);
}
Conah answered 15/1, 2015 at 17:20 Comment(5)
I actually tried that before. It results in another error: The navigation property 'Parent' is not a declared property on type 'Product'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property. Any suggestions?Rondo
it works in my case with the same Product class that I show in my answer. Did you declare the Parent property in the same way?Conah
Hello @ChrisKlingsater, I saw that you post a new question with that issue, did you deleted the foreign key attribute over the Parent property? Try to not merge Fluent Api with Data Annotations, it isn't a good practiceConah
Hi, yes I deleted the attribute prior to moving to fluent configuration.Rondo
I found the answer. For some reason I didn't write the example with an interface like the code was written with. When changing from the IProduct interface to the Product class your solution worked. Thanks! And sorry for the stupid typo :)Rondo

© 2022 - 2024 — McMap. All rights reserved.