Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple self referencing in Entity Framework fails with "principal end" error

I am trying to do the following with Entity Framework 6 and Code First:

public class Step
{
    public int Id { get; set; }
    public Step NextStepSuccess { get; set; }
    public Step NextStepFailure { get; set; }
}

The result however is:

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

When I remove one of the NextSteps, it works.

I already tried a lot of approaches using either Fluent API or attributes, but it seems I cannot get this working. From what I read, EF seems to try to connect my 2 NextStep properties in a parent->child relationship and then of course fails because the principal end is not defined. But in my case those properties are not part of the same relation.

like image 740
MuhKuh Avatar asked Sep 25 '22 15:09

MuhKuh


1 Answers

That is exacly the problem, EF is trying to create an one to one relationship and want that you specify which of your ends is the principal. If you want to create two different relationships, then I suggest you override OnModelCreating method of your context and add the following configurations:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Step>().HasRequired(s=>s.NextStepSuccess).WithMany();
  modelBuilder.Entity<Step>().HasOptional(s=>s.NextStepFailure).WithMany();

Choose to call HasRequired and HasOptional methods at your convenience.

like image 200
octavioccl Avatar answered Sep 28 '22 05:09

octavioccl