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; }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433

1 Answers1

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);
}
ocuenca
  • 38,548
  • 11
  • 89
  • 102
  • 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? – Chris Klingsater Jan 15 '15 at 18:48
  • 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? – ocuenca Jan 15 '15 at 19:29
  • 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 practice – ocuenca Jan 15 '15 at 20:44
  • Hi, yes I deleted the attribute prior to moving to fluent configuration. – Chris Klingsater Jan 16 '15 at 01:02
  • 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 :) – Chris Klingsater Jan 16 '15 at 01:02