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 模型 创建一个 ...
随机推荐
- MySQL服务器调优思路
1.mysqladmin -uroot ext|awk '/Queries/{q=$4}/Threads_connected/{c=$4}/Threads_running/{r=$4}END{prin ...
- 织梦dedecms 扩展channel栏目标签 获取交叉栏目名称和链接
channel栏目标签默认有调用顶级栏目(top).子栏目(son).同级栏目(self),那想获取交叉栏目的名称和链接怎么获取呢? 其实在原来的代码上改一下就可以了.下面是具体代码.打开文件chan ...
- Socket bind failed: [730048] ?????????×???(Э?é/???????/???)????í??错误
启动项目的时候发现tomcat跑不起来.后台输出错误Socket bind failed: [730048] ?????????×???(Э?é/???????/???)????í?? 发现是ecli ...
- TCP和UDP?
简单讲,TCP是打电话,UDP是发短信.
- ASP.WEB Form 几点知识
1.GridView 行的多选 <asp:TemplateField ControlStyle-Width="30" HeaderText="选择" &g ...
- Selenium-几种等待方式
强制等待 一直使用的time.sleep(5),可以放在任意地方,不好的地方,不太准确确定时间 隐形等待 driver.implicitly_wait(5) 设置了一个最长等待时间,如果在规定时间内网 ...
- MYSQL中获取得最后一条记录的语句
方法1:select max(id) from tablename 方法2:select last_insert_id(); 在MySQL中,使用auto_increment类型的id字段作为表的主键 ...
- Cookie是以文本文件保存在客户端的,所以说cookie对象从本质而言是 字符串,所以取值时用字符串,或其数组
- [原]NYOJ-A*B Problem II-623
大学生程序代写 A*B Problem II 时间限制:1000 ms | 内存限制:65535 KB 难度:1 描述 ACM的C++同学有好多作业要做,最头痛莫过于线性代数了,因为每次做到矩阵相 ...
- java将白色背景图片转换成透明图片
package evecom.image; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.Buffe ...