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 模型 创建一个 ...
随机推荐
- Python 3 面向对象 一
Python 3 面向对象 一.面向过程-->面向对象 面向过程:根据业务逻辑从上到下堆叠代码,即先干什么再干什么,基于面向过程去设计程序就好比在设计一条流水线,是一种机械式的思维方式 函数式: ...
- NFS指定端口,NFS缓存
nfs服务端: #编辑/etc/nfsmount.conf,在末尾添加: #RQUOTAD_PORT=30001#LOCKD_TCPPORT=30002#LOCKD_UDPPORT=30002#MOU ...
- 【反思】一个价值两天的BUG,无论工作还是学习C语言的朋友都看看吧!
博文原创,转载请联系博主! 使用C语言也有两个年头了,BUG写出来过不少,也改过不少BUG.但是偏偏就是有这么一个BUG让我手头的项目停工了两天,原因从百度找到谷歌,资料从MAN手册找到RFC也没有找 ...
- C++ STL中Map的按Key排序跟按Value排序
C++ STL中Map的按Key排序和按Value排序 map是用来存放<key, value>键值对的数据结构,可以很方便快速的根据key查到相应的value.假如存储学生和其成绩(假定 ...
- Python基础-列表推导式
python中列表推导式有三种数据类型可用:列表,字典,集合 列表推导式书写形式: [表达式 for 变量 in 列表] 或者 [表达式 for 变量 in 列表 if 条件] 1,列表推导式 ...
- Git_学习_06_ 放弃本地修改
一.未使用 git add 缓存代码时 git checkout -- filepathname // 放弃某个文件 git checkout . // 放弃所有文件 git checkout . 用 ...
- 文件操作类(QFileDialog、QFileInfo、QDir、QDirIterator、QFile)
一.QFileDialog 用于弹出打开或保存对话框,然后返回选择的文件或文件夹 1.可以筛选所需要的文件类型 2.可以设置是否多选 3.可以设置保存还是打开 二.QFileInfo 保存了文件相关信 ...
- linux命令学习笔记(12):more命令
more命令,功能类似 cat ,cat命令是整个文件的内容从上到下显示在屏幕上. more会以一页一页的显示方便 使用者逐页阅读,而最基本的指令就是按空白键(space)就往下一页显示,按 b 键就 ...
- I.MX6 FFmpeg 录制视频
/************************************************************************* * I.MX6 FFmpeg 录制视频 * 说明: ...
- sql根据坐标算距离
CREATE FUNCTION ConvertXYToDistance(@la1 DECIMAL,@lo1 DECIMAL,@la2 DECIMAL,@lo2 DECIMAL)RETURNS FLOA ...