多重性在关系中的角色中无效:EF 代码第一个具有相同主键和外键的一对一关系

Multiplicity is not valid in Role in relationship: EF code first one to one relationship with same primary key and foreign key

我有两个具有一对一关系的实体,其中目标实体的主键和外键相同。这是两个实体及其流畅的映射。

public class Register
{ 
    public int Id { get; set; }
    public string Number { get; set; }
    // N.B: Here I can't have this virtual property for my project dependencies.
    //public virtual CustomerDisplay CustomerDisplay { get; set; }
}

public class CustomerDisplay
{
    public int RegisterId { get; set; }
    public double ReceiptViewPercent { get; set; }
    public virtual Register Register { get; set; }
}

public class RegisterConfiguration : EntityConfig<Register>
{
    public RegisterConfiguration(bool useIdentity, bool sqlServerCe)
        : base(sqlServerCe)
    {
        this.HasKey(t => t.Id);

        if (!useIdentity)
        {
            Property(d => d.Id).IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }

        this.Property(t => t.Number).IsRequired().HasMaxLength(20);      
    }
}

public class CustomerDisplayConfiguration: EntityConfig<CustomerDisplay>
{
    public CustomerDisplayConfiguration(bool sqlServerCe)
        : base(sqlServerCe)
    {
        this.HasKey(t => t.RegisterId);      
        this.HasRequired(t => t.Register).WithMany().HasForeignKey(d => d.RegisterId).WillCascadeOnDelete(false);
    }
}

我收到以下错误:

我在 Whosebug 中看到了很多相关问题,但没有找到我的解决方案。这个最符合我的问题:

How to declare one to one relationship ...

谁能告诉我如何解决这个问题。谢谢

再次添加CustomerDisplay导航属性:

public class Register
{ 
    public int Id { get; set; }
    public string Number { get; set; }

    public virtual CustomerDisplay CustomerDisplay { get; set; }
}

并按照我显示的如下配置关系:

 this.HasRequired(t => t.Register).WithOptional(r=>r.CustomerDisplay);

请注意,您不需要使用 HasForeignKey 来指定 CustomerDisplay.CustomerId 是 FK。这是因为 Entity Framework 要求使用依赖的主键作为外键。由于别无选择,Code First 只会为您推断这一点。

更新

如果无法将CustomerDisplay导航属性添加到Registerclass中,那么我建议您建立一个单向的一对一关系。使用此配置:

this.HasRequired(t => t.Register);

这足以告诉 EF 在你们的关系中谁是主体,谁是依赖实体。