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 模型 创建一个 ...
随机推荐
- 【leetcode刷题笔记】Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For ...
- vary的用法
对于vary的用法,网上有许多种说法,云里雾里的,在此仅阐述一下本人的一些理解,首先是官方解释: Vary头域值指定了一些请求头域,这些请求头域用来决定: 当缓存中存在一个响应,并且该缓存没有过期失效 ...
- 基于socket实现上传文件
基于socket实现文件上传 客户端代码: #!/usr/bin/env python # -*- coding:utf-8 -*- """ 这个是实现上传文件 首先让客 ...
- POJ 2492 并查集 A Bug's Life
#include<iostream> #include<algorithm> #include<stdio.h> #include<string.h> ...
- Linux查看外网IP
Linux查看外网IP curl cip.cc curl ifconfig.me curl ipinfo.io
- Codeforces 448C Painting Fence:分治
题目链接:http://codeforces.com/problemset/problem/448/C 题意: 有n个木板竖着插成一排栅栏,第i块木板高度为a[i]. 你现在要将栅栏上所有地方刷上油漆 ...
- 英语发音规则---oo
英语发音规则---oo 一.总结 一句话总结: 1.重读音节词尾的字母组合oo发音素[u:]的音? too [tu:] adv.太;也 zoo [zu:] n.动物园 room [ru:m] n.房间 ...
- hash算法打散存储文件
1.首先,为防止一个目录下面出现太多文件,所以使用hash算法打散存储 举例代码: int hashcode = filename.hashCode();//得到hashCode int dir1 = ...
- 每天一个linux命令(6):rm命令
版权声明更新:2017-05-10博主:LuckyAlan联系:liuwenvip163@163.com声明:吃水不忘挖井人,转载请注明出处! 1文章介绍 本文介绍了Linux下面的rm命令. 2 开 ...
- [CJOJ2425][SYZOI Round1]滑稽的树
cjoj sol 子树转化成dfs序上的区间. 所以就变成了:区间Kth,区间内[a,b]范围内的数有多少个,单点修改 裸的树套树啊. code #include<cstdio> #inc ...