原文链接:https://www.entityframeworktutorial.net/code-first/cascade-delete-in-code-first.aspx

EF 6 Code-First系列文章目录:

当数据库的父记录被删除的时候,级联删除自动的删除相关的依赖记录,或者设置外键列为NULL。

EF 对于一对一,一对多,多对多关系,默认是启用了级联删除。

一对一关系中的级联删除

下面的Student和StudentAddress实体,是一对零或一的关系。

public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; } public virtual StudentAddress Address { get; set; }
} public class StudentAddress
{
[ForeignKey("Student")]
public int StudentAddressId { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public int Zipcode { get; set; }
public string State { get; set; }
public string Country { get; set; } public virtual Student Student { get; set; }
}

下面的操作,演示了级联删除。

using (var ctx = new SchoolContext())
{
var stud = new Student() { StudentName = "James" };
var add = new StudentAddress() { Address1 = "address" }; stud.Address = add; ctx.Students.Add(stud); ctx.SaveChanges(); ctx.Students.Remove(stud);// student and its address will be removed from db ctx.SaveChanges();
}

在上面的代码中,首先,EF保存stud和其StudentAddress实体到数据库中,然后删除stud,调用SaveChanges().EF就会删除stud,并且将StudentAddress表中相关级联一并删除。所以,EF默认是级联删除的。

一对多关系中的级联删除

下面的Student和Standard实体,是一对多关系。

public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; } public virtual Standard Standard { get; set; }
} public class Standard
{
public Standard()
{
Students = new List<Student>();
}
public int StandardId { get; set; }
public string Description { get; set; } public virtual ICollection<Student> Students { get; set; }
}

下面的代码,演示了一对多关系中的级联删除。

using (var ctx = new SchoolContext()) {

    var student1 = new Student() { StudentName = "James" };
var student2 = new Student() { StudentName = "Gandhi" }; var standard1 = new Standard() { StandardName = "Standard 1" }; student1.Standard = standard1;
student2.Standard = standard1; ctx.Students.Add(student1);
ctx.Students.Add(student2); //inserts students and standard1 into db
ctx.SaveChanges(); //deletes standard1 from db and also set standard_StandardId FK column in Students table to null for
// all the students that reference standard1.
ctx.Standards.Remove(standard1); ctx.SaveChanges();
}

在上面的例子中,EF从数据库中删除了standard1,并且设置Students表中的相关联的standard_StandardId外键列为null。

请注意:对于多对多关系,如果两个实体中的任何一个删除了,EF自动的删除中间表中相关的记录。

所以,EF默认是对所有的实体【一对一的中的实体、一对多中的实体、多对多中的实体】启用了级联删除。

关闭级联删除

可以用Fluent API中的WillCascadeOnDelete()来处理级联删除,例如:

public class SchoolContext<: DbContext
{
public SchoolContext():base("MySchool")
{
} public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>()
.HasOptional<Standard>(s => s.Standard)
.WithMany()
.WillCascadeOnDelete(false);
}
}

请注意:没有数据注解的特性,可以用来关闭级联删除。

15.翻译系列:EF 6中的级联删除【EF 6 Code-First 系列】的更多相关文章

  1. 20.2.翻译系列:EF 6中基于代码的数据库迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/code-based-migration-in-code-first.aspx EF 6 ...

  2. 20.1翻译系列:EF 6中自动数据迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/automated-migration-in-code-first.aspx EF 6 ...

  3. 20.翻译系列:Code-First中的数据库迁移技术【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/migration-in-code-first.aspx EF 6 Code-First ...

  4. 19.翻译系列:EF 6中定义自定义的约定【EF 6 Code-First约定】

    原文链接:https://www.entityframeworktutorial.net/entityframework6/custom-conventions-codefirst.aspx EF 6 ...

  5. 16.翻译系列:EF 6 Code -First中使用存储过程【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/entityframework6/code-first-insert-update-delete-stored ...

  6. 11.翻译系列:在EF 6中配置一对零或者一对一的关系【EF 6 Code-First系列】

    原文链接:https://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-fi ...

  7. 5.翻译系列:EF 6中数据库的初始化(EF 6 Code-First 系列)

    原文地址:http://www.entityframeworktutorial.net/code-first/database-initialization-in-code-first.aspx EF ...

  8. 7.翻译系列:EF 6中的继承策略(EF 6 Code-First 系列)

    原文地址:http://www.entityframeworktutorial.net/code-first/inheritance-strategy-in-code-first.aspx EF 6 ...

  9. 8.翻译系列: EF 6中配置领域类(EF 6 Code-First 系列)

    原文地址:http://www.entityframeworktutorial.net/code-first/configure-classes-in-code-first.aspx EF 6 Cod ...

随机推荐

  1. HDU 2389 Rain on your Parade 最大匹配(模板题)【HK算法】

    <题目链接> 题目大意:有m个宾客,n把雨伞,预计时间t后将会下大雨,告诉你每个宾客的位置和速度,每把雨伞的位置,问你最多几个宾客能够拿到伞. 解题分析: 本题就是要我们求人与伞之间的最大 ...

  2. Python常用模块--re

    Python内部的re--传闻中的正则模块,是无数初学者心中的噩梦,几乎到了谈正则色变的地步. 1.正则是干什么的 正则表达式,又称规则表达式.(英语:Regular Expression,在代码中常 ...

  3. 前端之HTML(一)

    最近学到前端的一些知识,感觉挺有意思的.总结一下常用的知识.这些只是最简单的东西. 一 HTML,CSS,JS的关系 一个基本的网站包含很多网页,一个网页又有html,css,js组成. html 是 ...

  4. Redis基础、应用、第三方支持组件总结

    这段时间一直在研究学习Redis的相关知识,现在大概做下总结吧首先,Redis的基础方面,不说配置,就单单说下Redis数据类型:Redis 五大数据类型有String 类型,Hash 类型,List ...

  5. 洛谷.4655.[CEOI2017]Building Bridges(DP 斜率优化 CDQ分治)

    LOJ 洛谷 \(f_i=s_{i-1}+h_i^2+\min\{f_j-s_j+h_j^2-2h_i2h_j\}\),显然可以斜率优化. \(f_i-s_{i-1}-h_i^2+2h_ih_j=f_ ...

  6. BZOJ.5285.[AHOI/HNOI2018]寻宝游戏(思路 按位计算 基数排序..)

    BZOJ LOJ 洛谷 话说vae去年的专辑就叫寻宝游戏诶 只有我去搜Mystery Hunt和infinite corridor了吗... 同样按位考虑,假设\(m=1\). 我们要在一堆\(01\ ...

  7. 洛谷P1309 瑞士轮(归并排序)

    To 洛谷.1309 瑞士轮 题目背景 在双人对决的竞技性比赛,如乒乓球.羽毛球.国际象棋中,最常见的赛制是淘汰赛和循环赛.前者的特点是比赛场数少,每场都紧张刺激,但偶然性较高.后者的特点是较为公平, ...

  8. Leetcode 记录(1~100)

    5.回文串 几种方法: 暴力:枚举每一个字串,判断是否为回文串,复杂度O(n^3),暴力月莫不可取 dp:区间dp思想,O(n^2) 中心扩展:找每一个字符,然后往两边扩展,O(n^2) manach ...

  9. 基于socketserver模块并发套接字

    1.基于tcp协议 服务端: import socketserverclass MyHandler(socketserver .BaseRequestHandler ): def handle(sel ...

  10. 怎么样从多列的DataTable里取需要的几列

    方法一: 也是广为人知的一种: YourDataTable.Columns.Remove("列名"); 但是这种情况只适合于去掉很少列的情况. 如果有很多列我却只要一两列呢,那就得 ...