简体   繁体   中英

Double self referencing in Entity Framework

When I'm trying to create a migration, Entity Framework throws an error

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

Code:

public class WorkFlowState
{
    public Guid Id { get; set; }

    public virtual WorkFlowState NextState { get; set; }
    public virtual WorkFlowState PrevState { get; set; }
}

What should I do?

Update 1: People are telling that the question is kind of duplicated question, but if you look at the accepted answer ( the third option which octavioccl provided ) you will see how it is different.

The problem is EF is trying to configure by convention an one-to-one relationship. If you check the link that was shared by @Michael in his comment, you will notice that you need to specify who is the principal end and who is the dependent end. When you are going to create a new instance of WorkflowState you must set always the principal end. Now, if you need to configure an one to one relationship, you will notice by that link you have two options:

Option 1: Specifying the FK of your relationship

public class WorkFlowState
{
     public Guid Id { get; set; }

     [Key,ForeignKey("PrevState")]
     public Guid PrevStateId { get; set; }
     public virtual WorkFlowState NextState { get; set; }
     public virtual WorkFlowState PrevState { get; set; }
}

Option 2: Using the Required data annotation:

public class WorkFlowState
{
     public Guid Id { get; set; }

     public virtual WorkFlowState NextState { get; set; }
     [Required]
     public virtual WorkFlowState PrevState { get; set; }
}

But there is a third option in case you need both references as optional:

public class WorkFlowState
{
     public Guid Id { get; set; }

     [ForeignKey("PrevState")]
     public Guid? PrevStateId { get; set; }

     [ForeignKey("NextState")]
     public Guid? NextStateId { get; set; }

     public virtual WorkFlowState NextState { get; set; }
     public virtual WorkFlowState PrevState { get; set; }
}

In this case you are going to create two unidirectional relationships. For help you understand better what happens in this last case, the Fluent Api configurations of these relationships would be this way:

modelBuilder.Entity<WorkFlowState>().HasOptional(t => t.NextState).WithMany().HasForeignKey(t => t.NextStateId);
modelBuilder.Entity<WorkFlowState>().HasOptional(t => t.PrevState).WithMany().HasForeignKey(t => t.PrevStateId);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM