实体框架代码首先是多层父子外键

时间:2014-04-19 12:57:34

标签: c# entity-framework collections parent-child hierarchy

我正在尝试使用Entity Framework 6实现层次结构,当我超越父子关系的第一级时,我遇到了麻烦。我想要做的一个例子如下:

[Table("TestParent", Schema = "dbo")]
public class TestParent {
    [Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int TestParentId { get; set; }

    private ICollection<TestChild> _testChildren;

    public virtual ICollection<TestChild> TestChildren {
        get { return _testChildren ?? (_testChildren = new HashSet<TestChild>()); }
        set { _testChildren = value; }
    }
}

[Table("TestChild", Schema = "dbo")]
public class TestChild {
    [Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int TestId { get; set; }

    [Key, ForeignKey("TestParent"), Column(Order = 2)]
    public int TestParentId { get; set; }
    public virtual TestParent TestParent { get; set; }

    private ICollection<TestGrandChild> _testGrandChildren;

    public virtual ICollection<TestGrandChild> TestGrandChildren {
        get { return _testGrandChildren ?? (_testGrandChildren = new HashSet<TestGrandChild>()); }
        set { _testGrandChildren = value; }
    }
}

[Table("TestGrandChild", Schema = "dbo")]
public class TestGrandChild {
    [Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int TestGrandChildId { get; set; }

    [Key, Column(Order = 2)]
    public int TestChildId { get; set; }
    public virtual TestChild Test { get; set; }
}

由于某些原因,EF无法识别TestGrandChild.TestChildIdTestChild.TestChildId的外键。如果我试着像这样强迫它:

[Table("TestGrandChild", Schema = "dbo")]
public class TestGrandChild {
    [Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual int TestGrandChildId { get; set; }

    [Key, ForeignKey("TestChild"), Column(Order = 2)]
    public int TestChildId { get; set; }

    public virtual TestChild Test { get; set; }
}

我收到以下错误:

  

System.Reflection.TargetInvocationException:调用目标抛出了异常。 ---&GT; System.Data.Entity.ModelConfiguration.ModelValidationException:在模型生成期间检测到一个或多个验证错误:   TestGrandChild_TestChild_Target_TestGrandChild_TestChild_Source ::关系约束中的从属角色和主要角色中的属性数必须相同。

让我疯狂!!!!

1 个答案:

答案 0 :(得分:3)

TestChild具有由(TestId, TestParentId)组成的复合主键。因此,引用TestGrandChild的{​​{1}}中的外键也必须具有相同数量的部分 - 这是异常所说的内容。

TestChild应如下所示:

TestGrandChild

[Table("TestGrandChild", Schema = "dbo")] public class TestGrandChild { [Key, Column(Order = 1), DatabaseGenerated(DatabaseGeneratedOption.Identity)] public virtual int TestGrandChildId { get; set; } [Key, ForeignKey("TestChild"), Column(Order = 2)] public int TestId { get; set; } [Key, ForeignKey("TestChild"), Column(Order = 3)] public int TestParentId { get; set; } public virtual TestChild TestChild { get; set; } } 现在有一个复合键TestGrandChild,最后两个部分(TestGrandChildId, TestId, TestParentId)形成(TestId, TestParentId)中主键(TestId, TestParentId)的复合外键。< / p>