先在EF代码中创建多个外键引用同一个table

Create multiple foreign keys referes to the same table in EF code first

在我的 table 中它有两个外键指向同一个 table。当我进行迁移时(Entity Framework 代码优先方法)它弹出错误,

“在模型生成过程中检测到一个或多个验证错误: Dog_Sire_Target::多重性在关系 'Dog_Sire' 中的角色 'Dog_Sire_Target' 中无效。因为Dependent Role属性不是关键属性,所以Dependent Role的重数上限必须是'*'.".

但是,如果我只添加一个外键,它就可以正常工作。这是我的 table 结构。

public class Dog
{
[Key]

public int Dog_Id { get; set; }

public string Dog_Name { get; set; }

[ForeignKey("Sire")]

public int? Dog_SireId { get; set; }

[ForeignKey("Dam")]

public int? Dog_DamId { get; set; }

[ForeignKey("Dog_SireId")]

public virtual Dog Sire { get; set; }

[ForeignKey("Dog_DamId")]

public virtual Dog Dam { get; set; }
}

试试这个模型:

public class Dog
{
    [Key]
    public int DogID { get; set; }
    public string DogName { get; set; }

    public int? DogSireID { get; set; }
    [ForeignKey("DogSireID")]
    public virtual Dog DogSire { get; set; }

    public int? DogDamID { get; set; }
    [ForeignKey("DogDamID")]
    public virtual Dog DogDam { get; set; }

    [InverseProperty("DogSire")]
    public virtual ICollection<Dog> DogsSires { get; set; }
    [InverseProperty("DogDam")]
    public virtual ICollection<Dog> DogsDams { get; set; }
}