1

I have a class called Person

public class Contact
{
    public int ID{get;set;}
    public string Name{get; set;}
    public Contact Secretary{get; set;}
    public Contact Assistant{get; set;}
}

When I try to do data migrations I get the following error.

 Unable to determine the principal end of an association between the types 
'MyApp.Contact' and 'MyApp.Contact'. The principal end of this association must be 
explicitly configured using either the relationship fluent API or data annotations.

If I remove one of the two "Contact" types the error goes away. How do I have two contact types in the class? I would like to work thru this error using Data Annotations if possible. But am not sure where to start with this one.

Nate
  • 30,286
  • 23
  • 113
  • 184
John S
  • 7,909
  • 21
  • 77
  • 145
  • Have you tried the `[ForeignKey("IdParent")]` attribute? -- http://stackoverflow.com/q/9759679/86860 – Nate Feb 19 '14 at 20:12
  • You can't set up two foreign keys to the same type using just data annotations, you need to use the fluent API. See, for example, http://social.msdn.microsoft.com/Forums/en-US/08bba96a-20b2-4a3c-9e0e-a5475b703dfe/code-first-self-referencing-foreign-key?forum=adodotnetentityframework – Michael Edenfield Feb 19 '14 at 20:19

1 Answers1

1

Here's an example of some configuration that would work for you, I think. You might want to explicitly specify the foreign key names as they default to using the type of the entity rather than the name of the navigation property.

public class MyContext : DbContext
{
    public DbSet<Contact> Contacts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        var contactConfiguration = new EntityTypeConfiguration<Contact>();
        contactConfiguration.HasOptional(c => c.Secretary).WithOptionalPrincipal();
        contactConfiguration.HasOptional(c => c.Assistant).WithOptionalPrincipal();

        modelBuilder.Configurations.Add(contactConfiguration);
    }
}
Josh Gallagher
  • 5,211
  • 2
  • 33
  • 60