我有一堆彼此相关的类。
让我们以下面的类层次结构为例:
Class A
{
// PK
public string A_Id
// Navigation Property
public virtual ICollection<B> MyB{ get; set; }
}
Class B
{
// PK
public int B_Id
// FK - On Delete - NO ACTION <---------- Difference here
public string A_Id { get; set; }
// Navigation Properties
public virtual A MyA { get; set; }
public List<C> MyC{ get; set; }
}
Class C
{
// PK
public int C_Id
// FK - On Delete - CASCADE <---------- Difference here
public int B_Id { get; set; }
// Navigation Properties
public virtual B MyB { get; set; }
}
当我在 SQL Management Studio 中检查 FK 时,我看到 On delete cascade 是在 Class C's FK 上定义的,但不是在 Class B's FK 上定义的强>.
另外,当我尝试删除 A 的一个实例时,我得到了不同的运行时异常,因为有些行引用了该实例。
Why is this happening?
What should I do to define them both to On Delete Cascade?
How EF6 determines how to define the FKs??
我已经阅读了很多没有成功的 SO 答案。
我还尝试使用 Fluent API 定义 FK,但它只是创建了第二个 FK 而不是修改第一个。 =[
最佳答案
好吧,经过一番努力,这里是正确的答案:
Entity Framework 默认行为是“On Delete Cascade”
但它只能在列为 Non-Nullable 时定义“ON DELETE CASCADE”。
因此,如果我们回到示例,我们可以看到 A 类有一个 string PK(nullable),B 类有一个 int PK(不可空)。这就解释了差异。
如何解决?
The best solution is to set a [Required] attribute above the FK property, otherwise, the EF6 engine will treat that property as nullable and define On Delete -> No Action!
工作示例:
Class A
{
// PK
public string A_Id
// Navigation Property
public virtual ICollection<B> MyB{ get; set; }
}
Class B
{
// PK
public int B_Id
// FK - On Delete - NO ACTION <---------- Difference here
[Required] <------------------------ SOLUTION =] =] =]
public string A_Id { get; set; }
// Navigation Properties
public virtual A MyA { get; set; }
public List<C> MyC{ get; set; }
}
Class C
{
// PK
public int C_Id
// FK - On Delete - CASCADE <---------- Difference here
public int B_Id { get; set; }
// Navigation Properties
public virtual B MyB { get; set; }
}
关于c# - Entity Framework 6 如何决定是否应使用 ON DELETE CASCADE 定义 FK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51239910/