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);