在关系中,角色中的多重性无效:EF code first使用相同的主键和外键建立一对一关系。

3

我有两个实体,它们之间存在一对一的关系,其中目标实体的主键和外键相同。以下是两个实体及其流畅映射。

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

我遇到了以下错误:

enter image description here

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

如何使用Entity Framework 4 Code First POCO声明一对一关系...

请问有谁能告诉我如何解决这个问题?谢谢
1个回答

3
重新添加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,你们关系中的主体和从属实体是谁了。

很抱歉,由于我的项目依赖关系,我无法将CustomerDisplay导航属性添加到Register类中。因此,我在该实体中作为注释放了一个说明。我必须找到另一种解决方案,而不是将CustomerDisplay导航属性添加到Register类中。 - Hannan Hossain

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接