原文链接: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 2553 n皇后问题【DFS递归解法】

    <题目链接> 题目大意: Problem Description 在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45 ...

  2. springboot2 config_toolkit 并且设置全局获取数据GlobalUtil

    本文只贴相关代码段,完整代码请移步至本人github,若是喜欢,可以star给予支持 作者:cnJun 博客专栏: https://www.cnblogs.com/cnJun/ 本文实现目标 重要的配 ...

  3. linux 硬盘分区与格式化挂载 (二)

    1. 文件系统的挂载与卸载(详见linux系统管理P406)1) 掌握挂载的定义:挂载指将一个设备(通常是存储设备)挂接到一个已存在的目录上.2) 掌握mount命令的功能:实现文件系统的挂载.3) ...

  4. LR特征维数特别大实时计算问题

    美团 https://tech.meituan.com/machinelearning-data-feature-process.html 维数灾难 待续...

  5. [python] 查询mysql返回datetime类型数据的处理

    Python 查询Mysql,如果是datetime类型,在json序列化的时候会出现问题. 在网上查了一下,解决方案基本都是遍历dict数据,如果是datetime则转化为字符串. from dat ...

  6. BZOJ.1535.[POI2005]SZA-Template(KMP DP)

    BZOJ 洛谷 \(Description\) 给定一个字符串\(s\),求一个最短的字符串\(t\)满足,将\(t\)拼接多次后,可以得到\(s\).拼接是指,可以将\(t\)放在当前串的任意位置, ...

  7. HNOI 2017

    题目链接 我还是按bzoj AC数量排序做的 4827 这个其实如果推一下(求每个值)式子会发现是个卷积,然后FFT就好了 4826 记不太清了,可以求出每个点左右第一个比他的的点的位置,将点对看成平 ...

  8. PA2015

    题目链接 我按AC排序后做的 4291 傻逼题不多说 4292 f(n)最大也很小,暴力枚举就好了 4293 这是个线段树的题,说到这应该会了 4294 Claris:斐波那契数列模\(10^m\)的 ...

  9. pip安装django失败

    pip install django时提示 Cannot fetch index base URL https://mirrors.tuna.tsinghua.edu.cn/pypi/simple/, ...

  10. 关于linux kernel slab内存管理的一点思考

    linux kernel 内存管理是个很大的话题,这里记录一点个人关于slab模块的一点思考总结. 有些书把slab介绍成高速缓存,这会让人和cache,特别是cpu cache混淆,造成误解.sla ...