c# - Entity Framework 6 如何决定是否应使用 ON DELETE CASCADE 定义 FK

标签 c# sql .net database entity-framework-6

我有一堆彼此相关的类。

让我们以下面的类层次结构为例:

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/

相关文章:

c# - 如何循环并检查 C# 中的用户输入是否正确?

c# - 在绑定(bind)到 ListView 之前修改 ViewModel 的属性

sql - 如何在分区的 MySQL 数据库中的字段上添加唯一索引?

C# 如何通过管理员提升的 cmd 运行进程(带参数)

c# - 如何在运行时将 IL 注入(inject)方法

c# - 我应该将 SQL Server UNIQUEIDENTIFIER 检索到哪种 C# 数据类型?

c# - Streamwriter 未写入文件

php - Laravel Query Builder 其间

python - SQLite:选择所有日期值对,其中每个日期和第一个日期之间的距离是特定时间段的倍数

c# - 是否有任何功能或工具(免费)可以将任何 .Net 类型名称自动完成为完全限定名称?