原文链接: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. 001.NoSQL及MongoDB简介

    一 NoSQL简介 二 分布式系统 三 CAP及BASE定律 以上均可参考: http://www.runoob.com/mongodb/nosql.html 四 MongoDB简介 参考:http: ...

  2. Window通过zip安装并启动mariadb

    下载解压后进入bin目录 使用mysql_install_db.exe工具:https://mariadb.com/kb/en/mariadb/mysql_install_dbexe/ 安装完成后,在 ...

  3. 【ACM】 1231 最大连续子序列

    [1231 最大连续子序列 ** Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) To ...

  4. IntelliJ IDEA classpath包含哪些文件夹以及如何把文件(夹)添加到classpath下

    在IDEA中,标为蓝色的文件夹被认定为包含在classpath中,例如上图中的resources.src文件夹.把文件位置以"classpath:applicationContext.xml ...

  5. 多角度对比 ES5与ES6的区别

    ES5与ES6的对比不同点整理 本文关键词:ES6,javascript, 1.Default Parameters(默认参数) es6之前,定义默认参数的方法是在一个方法内部定义 var link ...

  6. Python3从零开始爬取今日头条的新闻【二、首页热点新闻抓取】

    Python3从零开始爬取今日头条的新闻[一.开发环境搭建] Python3从零开始爬取今日头条的新闻[二.首页热点新闻抓取] Python3从零开始爬取今日头条的新闻[三.滚动到底自动加载] Pyt ...

  7. [OPENCV]cvHoughLines2使用说明

    1.cvHoughLines2函数定义: CvSeq *cvHoughLines2 { CvArr *image, void *line_storage, int method, double rho ...

  8. Hass.io: add-on Configurator

    {   "username": "admin",   "password": "admin",   "cert ...

  9. K Besk [POJ 3111]

    描述 Demy有n颗宝石.她的每个珠宝都有一些价值vi和重量wi.自从丈夫约翰在最近的金融危机爆发后,已经决定出售一些珠宝.她决定自己会保留最好的珠宝.她决定保留这样的宝石,使他们的具体价值尽可能大. ...

  10. invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific

    今天写vfl自动给布局之时,出现了 invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific- break on _C ...