Double self referencing in Entity Framework

倖福魔咒の 提交于 2021-01-28 03:50:46

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/31938771/double-self-referencing-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!