繁体   English   中英

多重性在关系中的角色中无效: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);
    }
}

我收到以下错误:

在此输入图像描述

我在stackoverflow中看到了很多相关的问题,但没有找到我的解决方案。 这个与我的问题最匹配:

如何宣布一对一的关系......

任何人都可以告诉我如何摆脱这个问题。 谢谢

再次添加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导航属性添加到Register类中,那么我建议您创建单向一对一关系。 使用此配置:

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

这足以告诉EF谁是委托人,谁是你关系中的依赖实体。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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