Cascade Delete in Entity Framework Code-First:

Cascade delete automatically deletes dependent records or set null to foreignkey properties when the principal record is deleted.

Cascade delete is enabled by default in Entity Framework for all types of relationships such as one-to-one, one-to-many and many-to-many.

Cascade delete in one-to-one relationship:

Consider the following Student and StudentAddress entities that have one-to-zero-or-one relationship.

public class Student
{
public 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; }
}

The following example demonstrates cascade delete operation when Student is removed.

using (var ctx = new SchoolContext()) {

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

In the above example, first it saves student and studentAddress into database and then when it removes student1 and call SaveChanges(), EF will delete student1 as well as its StudentAddress from the database. Thus, EF enables cascade delete by default.

Cascade Delete in One-to-Many Relationship:

Consider the following Student and Standard entities that have one-to-many relationship.

public class Student
{
public 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; }
}

The following example demonstrates cascade delete effect between entities that have one-to-many relationship.

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();
}

In the above example, it deletes standard1 from db and also set standard_StandardId FK column in Students table to null for all the records that reference standard1.

EF automatically deletes related records in the middle table for many-to-many relationship entities if one or other entity is deleted.

Thus, EF enables cascading delete effect by default for all the entities.

Turn off cascading delete:

Use Fluent API to configure entities to turn off the cascading delete as shown below.

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);
}
}

Note: DataAnnotations does not include any attribute to turn off cascading delete.

Entity Framework Code-First(15):Cascade Delete的更多相关文章

  1. Entity Framework Tutorial Basics(15):Querying with EDM

    Querying with EDM: We have created EDM, DbContext, and entity classes in the previous sections. Here ...

  2. Entity Framework Code first(转载)

    一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...

  3. Entity Framework Code First (三)Data Annotations

    Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表 ...

  4. Entity Framework Code First (二)Custom Conventions

    ---------------------------------------------------------------------------------------------------- ...

  5. Entity Framework Code First (一)Conventions

    Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通 ...

  6. Entity Framework Tutorial Basics(11):Code First

    Code First development with Entity Framework: Entity Framework supports three different development ...

  7. Entity Framework Code First (七)空间数据类型 Spatial Data Types

    声明:本文针对 EF5+, Visual Studio 2012+ 空间数据类型(Spatial Data Types)是在 EF5 中引入的,空间数据类型表现有两种: Geography (地理学上 ...

  8. Entity Framework Code First (四)Fluent API - 配置属性/类型

    上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Flu ...

  9. Entity Framework Code First (八)迁移 Migrations

    创建初始模型和数据库 在开始使用迁移(Migrations)之前,我们需要一个 Project 和一个 Code First Model, 对于本文将使用典型的 Blog 和 Post 模型 创建一个 ...

随机推荐

  1. 【leetcode刷题笔记】Subsets II

    Given a collection of integers that might contain duplicates, S, return all possible subsets. Note: ...

  2. Android系统篇之—-编写系统服务并且将其编译到系统源码中【转】

    本文转载自:http://www.wjdiankong.cn/android%E7%B3%BB%E7%BB%9F%E7%AF%87%E4%B9%8B-%E7%BC%96%E5%86%99%E7%B3% ...

  3. 为UniDBEdit添加拖拽属性

    不知是作者Fashard的疏忽还是有意,UniDBEdit的拖拽属性居然没有发布出来(其他组件都已发布).加上其实也很简单. 打开source目录下的uniDBEdit.pas单元,在TUniDBEd ...

  4. Sqoop- sqoop将mysql数据表导入到hive报错

    sqoop将mysql数据表导入到hive报错 [root@ip---- lib]# sqoop import --connect jdbc:mysql://54.223.175.12:3308/gx ...

  5. 洛谷p3369 treap

    这是一个treap裸题,还可以用splay,替罪羊树,线段树等等写 treap是树和堆结合,可以方便的在O(log(n))期望时间内进行以下操作,因此treap又叫做名次树 插入x数 删除x数(若有多 ...

  6. error: reference to 'max' is ambiguous

    1.     自定义的变量名    与      库中的      重名了

  7. Unity3D之Mesh(七)绘制长方体

    前言: 从现在开始,终于感觉进入一点点正题了!动态创建三维立体模型mesh!依然从简单入手:长方体. 一.基本思路 由于是创建长方体mesh,由之前的研究得知,两个数据必须要有,即:顶点的数据:ver ...

  8. 防止未登录用户操作—struts2拦截器简单实现(转)

    原文地址:http://blog.csdn.net/zhutulang/article/details/38351629 尊重原创,请访问原地址 一般,我们的web应用都是只有在用户登录之后才允许操作 ...

  9. jmeter--简单使用

    1.启动jmeter 2.创建线程组 2.点击线程组,选择添加,选择sampler(采样器),选择http请求 3.在添加的请求页面中,填写服务器名称或IP,端口,路径,请求的方法 4.添加请求的参数 ...

  10. 【Educational Codeforces Round 37】F. SUM and REPLACE 线段树+线性筛

    题意 给定序列$a_n$,每次将$[L,R]$区间内的数$a_i$替换为$d(a_i)$,或者询问区间和 这题和区间开方有相同的操作 对于$a_i \in (1,10^6)$,$10$次$d(a_i) ...