Entity Framework Code-First(15):Cascade Delete
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的更多相关文章
- Entity Framework Tutorial Basics(15):Querying with EDM
Querying with EDM: We have created EDM, DbContext, and entity classes in the previous sections. Here ...
- Entity Framework Code first(转载)
一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...
- Entity Framework Code First (三)Data Annotations
Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表 ...
- Entity Framework Code First (二)Custom Conventions
---------------------------------------------------------------------------------------------------- ...
- Entity Framework Code First (一)Conventions
Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通 ...
- Entity Framework Tutorial Basics(11):Code First
Code First development with Entity Framework: Entity Framework supports three different development ...
- Entity Framework Code First (七)空间数据类型 Spatial Data Types
声明:本文针对 EF5+, Visual Studio 2012+ 空间数据类型(Spatial Data Types)是在 EF5 中引入的,空间数据类型表现有两种: Geography (地理学上 ...
- Entity Framework Code First (四)Fluent API - 配置属性/类型
上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Flu ...
- Entity Framework Code First (八)迁移 Migrations
创建初始模型和数据库 在开始使用迁移(Migrations)之前,我们需要一个 Project 和一个 Code First Model, 对于本文将使用典型的 Blog 和 Post 模型 创建一个 ...
随机推荐
- Spring Cloud之Swagger集群搭建
在微服务中,Swagger是每个服务 比如会员服务,订单服务,支付服务 进行继承. 如何将整个微服务中的Swagger进行合成,同一台服务器上. 使用Zuul+Swagger实现管理整个微服务API文 ...
- castle windsor学习----ComponentModel construction contributors
public class RequireLoggerProperties : IContributeComponentModelConstruction { public void ProcessMo ...
- Struts2的工作流程分析
Struts2的工作流程分析 Posted on 2011-02-22 09:32 概述 本章讲述Struts2的工作原理. 读者如果曾经学习过Struts1.x或者有过Struts1.x的开发经验, ...
- fastjson 格式化自定义选项
QuoteFieldNames———-输出key时是否使用双引号,默认为true WriteMapNullValue——–是否输出值为null的字段,默认为false WriteNullNumberA ...
- 2.HelloWorld程序
1.流程图 2./itcast0711/src/main/java/cn/itcast/a_helloworld/HelloWorld.java package cn.itcast.a_hellowo ...
- Oracle的PL_SQL的结构
--PL/SQL的结构 declare --声明变量和常量关键字 v_name nvarchar2(); v_age integer;--常规变量声明 v_product table_name.col ...
- BZOJ 2431 [HAOI2009]逆序对数列:dp 逆序对
题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=2431 题意: 给定n,k,问你有多少个由1~n组成的排列,使得逆序对个数恰好为k个. 题解 ...
- js 禁止用户使用Ctrl+鼠标滚轮缩放网页
为什么会有人会使用ctrl+鼠标滚轮缩放网页?坚决禁止! <html> <head> <title>测试</title> <script lang ...
- js 判断滚动条的滚动方向
以下代码实现判断页面的滚动条的滚动方向: var sign = 80;//定义默认的向上滚与向下滚的边界 window.onscroll = window.onresize = function(){ ...
- php 设置页面导航动态active类样式的添加
在用php制作项目中,一般都是把页头和页脚分离出来.页头导航在选中状态时会有一些样式,例如active等,当页面在首页时候,导航的首页也应该是active的样式,那么,怎么用php控制这些样式的添加和 ...