有人能说清楚吗? 我有三个对象。首先是Root对象
public class Root
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
这是我的复合键的基础,用于Parent,Child:
public class Parent
{
[Key, Column(Order = 0)]
public int RootId { get; set; }
public Root Root { get; set; }
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public ICollection<Child> Children { get; set; } = new Collection<Child>();
}
public class Child
{
[Key, Column(Order = 0)]
public int RootId { get; set; }
public Root Root { get; set; }
[Key, Column(Order = 1)]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int ParentId { get; set; }
[ForeignKey("RootId, ParentId")]
public Parent Parent { get; set; }
}
我添加了一个包含多个孩子的新父对象
Parent result = new Parent
{
RootId = rootId
};
foreach (var child in children)
{
result.Children.Add(new Child
{
RootId = rootId
});
}
_dbContext.Parents.Add(result);
_dbContext.Save();
但是,每当我在数据库中有多个Root对象时,我就会收到异常:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Children_dbo.Parents_RootId_ParentId". The conflict occurred in database "Test", table "dbo.Parents".
当我删除数据库中的外键约束时,我可以看到EF以某种方式忽略了我设置的RootId = rootId
。它使用不同的一个。 ParentId已正确设置,但显然这会导致FK不存在。
我想在一次Save调用中提交父级及其子级。在将父级添加到_dbContext.Parents之后,我尝试将子项添加到_dbContext.Children,我尝试首先添加子项,但无济于事。
有人可以解释一下吗?我已经没有关于要检查什么来理解我做错了什么的想法......
编辑:我正在使用Entity Framework 6.1.3。