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 模型 创建一个 ...
随机推荐
- nginx location 语法
location 语法location 有”定位”的意思, 根据Uri来进行不同的定位.在虚拟主机的配置中,是必不可少的,location可以把网站的不同部分,定位到不同的处理方式上.比如, 碰到.p ...
- 在Treeview中节点的data属性中保存记录类型及其消除的办法
一.保存记录类型在data指针中: procedure TForm1.getheaditems(pp:TfrxBand;hnode:THeadTreeNode;var i:Integer;var j: ...
- linux 磁盘管理与文件系统
一.磁盘分区的意义 磁盘分区就是为了将磁盘分成不同的逻辑区域,每个分区可以有不同的文件系统 二. 磁盘分区是按照磁盘的柱面进行分区的,由于盘片在转动时的角速度都是一样的,所以磁头在最外层的磁道上读取信 ...
- HTML5 Video Blob
我的博客搬家到https://www.w2le.com/了 <video src="blob:http://www.bilibili.com/d0823f0f-2b2a-4fd6-a9 ...
- vps 虚拟机 云服务器
vps :wxmp 03服务器 虚拟主机: 万网免费主机 云服务器:wxmp阿里云
- 使用mybatis-generator插件结合tk.mybatis自动生成mapper二三事
本篇文章将介绍使用spring boot框架,引入mybatis-generator插件,结合tk.mybatis自动生成Mapper和Entity的一整套流程,其中包括最重要的踩坑与填坑. ...
- Struts2与OGNL
Action会自动放入值栈,成员变量会自动放入root区 如果是方法中的对象 要放入值栈 push()或者getRoot().push(); 界面取值 直接用对象的属性名进行取值
- http接口测试框架-遇到的问题
遇到过很多问题 如图,结果做作对比的时候,发现返回的结果有一个error_code: 0,中间有一个空格,导致对比失败 解决方法:打印出结果,再对比,case里的预期结果是否一致,有时候是填写的错误 ...
- Vue从接口请求数据
<!doctype html> <html> <head> <meta charset="UTF-8"> <title> ...
- Core Data存储数据出错(This NSPersistentStoreCoordinator has no persistent stores (unknown))
Core Data存储数据的时候崩溃,崩溃信息: reason: 'This NSPersistentStoreCoordinator has no persistent stores (unknow ...