EF Core中DeleteBehavior的介绍(转自MSDN)

Delete behaviors

Delete behaviors are defined in the DeleteBehavior enumerator type and can be passed to the OnDelete fluent API to control whether the deletion of a principal/parent entity or the severing of the relationship to dependent/child entities should have a side effect on the dependent/child entities.
There are three actions EF can take when a principal/parent entity is deleted or the relationship to the child is severed:

  • The child/dependent can be deleted
  • The child‘s foreign key values can be set to null
  • The child remains unchanged
Note
The delete behavior configured in the EF Core model is only applied when the principal entity is deleted using EF Core and the dependent entities are loaded in memory (that is, for tracked dependents). A corresponding cascade behavior needs to be setup in the database to ensure data that is not being tracked by the context has the necessary action applied. If you use EF Core to create the database, this cascade behavior will be setup for you.

For the second action above, setting a foreign key value to null is not valid if foreign key is not nullable. (A non-nullable foreign key is equivalent to a required relationship.) In these cases, EF Core tracks that the foreign key property has been marked as null until SaveChanges is called, at which time an exception is thrown because the change cannot be persisted to the database. This is similar to getting a constraint violation from the database.

There are four delete behaviors, as listed in the tables below.

Optional relationships
For optional relationships (nullable foreign key,或者根本就没设置外键) it is possible to save a null foreign key value, which results in the following effects:

Behavior Name Effect on dependent/child in memory Effect on dependent/child in database
Cascade Entities are deleted Entities are deleted
ClientSetNull (Default) Foreign key properties are set to null None
SetNull Foreign key properties are set to null Foreign key properties are set to null
Restrict None None

Required relationships
For required relationships (non-nullable foreign key) it is not possible to save a null foreign key value, which results in the following effects:

Behavior Name Effect on dependent/child in memory Effect on dependent/child in database
Cascade (Default) Entities are deleted Entities are deleted
ClientSetNull SaveChanges throws None
SetNull SaveChanges throws SaveChanges throws
Restrict None None

In the tables above, None can result in a constraint violation. For example, if a principal/child entity is deleted but no action is taken to change the foreign key of a dependent/child, then the database will likely throw on SaveChanges due to a foreign constraint violation.

At a high level:

  • If you have entities that cannot exist without a parent, and you want EF to take care for deleting the children automatically, then use Cascade.

    • Entities that cannot exist without a parent usually make use of required relationships, for which Cascade is the default.
  • If you have entities that may or may not have a parent, and you want EF to take care of nulling out the foreign key for you, then use ClientSetNull
    • Entities that can exist without a parent usually make use of optional relationships, for which ClientSetNull is the default.
    • If you want the database to also try to propagate null values to child foreign keys even when the child entity is not loaded, then use SetNull. However, note that the database must support this, and configuring the database like this can result in other restrictions, which in practice often makes this option impractical. This is why SetNull is not the default.
  • If you don‘t want EF Core to ever delete an entity automatically or null out the foreign key automatically, then use Restrict. Note that this requires that your code keep child entities and their foreign key values in sync manually otherwise constraint exceptions will be thrown.

原文链接

原文地址:https://www.cnblogs.com/OpenCoder/p/9819226.html

时间: 2024-10-31 13:51:30

EF Core中DeleteBehavior的介绍(转自MSDN)的相关文章

EF Core 中DbContext不会跟踪聚合方法和Join方法返回的结果

EF Core中: 如果调用Queryable.Count等聚合方法,不会导致DbContext跟踪(track)任何实体. 此外调用Queryable.Join方法返回的匿名类型也不会被DbContext所跟踪(实测调用Queryable.Join方法返回EF Core中的实体类型也不会被DbContext所跟踪). Queryable.Count等聚合方法和Queryable.Join方法返回的结果不会被跟踪,原因是因为这两种方法返回的结果类型并没有被DbContext的OnModelCre

EF Core中执行Sql语句查询操作之FromSql,ExecuteSqlCommand,SqlQuery

一.目前EF Core的版本为V2.1 相比较EF Core v1.0 目前已经增加了不少功能. EF Core除了常用的增删改模型操作,Sql语句在不少项目中是不能避免的. 在EF Core中上下文,可以返货DbConnection ,执行sql语句.这是最底层的操作方式,代码写起来还是挺多的. 初次之外 EF Core中还支持 FromSql,ExecuteSqlCommand 连个方法,用于更方便的执行Sql语句. 另外,目前版本的EF Core 不支持SqlQuery,但是我们可以自己扩

EF Core中的DB First与Code First

前言: 大家都习惯在程序中生成对应的model来对数据库进行操作,所以如何快速的生成数据库表的对应model,是基础之一.总结了一下在我的认知中大概是这个结构: Db first方式: 先创建好对应的数据库通过数据库来生成对应的Model. 1 创建数据库 大家可根据自己的需要生成对应的数据库,这里只做演示所以使用官方给的SqlServer数据库脚本: CREATE DATABASE [Blogging]; GO USE [Blogging]; GO CREATE TABLE [Blog] (

EF Core 中实现 动态数据过滤器

前言 在项目开发中,我们很多时候都会设计  软删除.所属用户 等等一系列字段 来方便我们在业务查询的时候进行各种过滤 然后引申的问题就是: 在业务查询的时候,我们要如何加上这些条件?或者动态禁用某些查询条件呢? EF Core自带的全局过滤查询功能 EF Core提供了一个HasQueryFilter 供我们在查询的时候进行预置部分筛选条件 例如:     builder.HasQueryFilter(x => !x.IsDelete); 这样查询的时候  EF Core 会自动帮我们实现过滤

EF Core中如何设置数据库表自己与自己的多对多关系

本文的代码基于.NET Core 3.0和EF Core 3.0 有时候在数据库设计中,一个表自己会和自己是多对多关系. 在SQL Server数据库中,现在我们有Person表,代表一个人,建表语句如下: CREATE TABLE [dbo].[Person]( [PersonID] [int] IDENTITY(1,1) NOT NULL, [Name] [nvarchar](50) NULL, [Age] [int] NULL, CONSTRAINT [PK_Person] PRIMARY

ef core中如何实现多对多的表映射关系

文档:https://docs.microsoft.com/en-us/ef/core/modeling/relationships class MyContext : DbContext { public DbSet<Post> Posts { get; set; } public DbSet<Tag> Tags { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { m

EF Core 2.0中如何手动映射数据库的视图为实体

由于Scaffold-DbContext指令目前还不支持自动映射数据库中的视图为实体,所以当我们想使用EF Core来读取数据库视图数据的时候,我们需要手动去做映射,本文介绍如何在EF Core中手动映射数据库的视图为实体. 假设我们在SQL Server中有如下数据库视图[dbo].[V_Person]: CREATE VIEW [dbo].[V_Person] AS SELECT ID, Code, Name, CreateTime, UpdateTime FROM dbo.Person G

EF Core 新特性——Owned Entity Types

Owned Entity Types 首先owned entity type是EF Core 2.0的新特性. 至于什么是owned entity types,可以先把他理解为EF Core官方支持的值对象. 值对象 举一个简单的例子,你可能在开发中经常遇到,订单,地址,地址簿的关系: public class Order { public int Id { get; set; } public string Name { get; set; } public double Price { ge

EF Core 快速上手——EF Core 入门

EF Core 快速上手--EF Core 介绍 本章导航 从本书你能学到什么 对EF6.x 程序员的一些话 EF Core 概述 1.3.1 ORM框架的缺点 第一个EF Core应用 ??本文是对<Entity framework in action>部分章节的翻译,某些场景也会附上笔者实践的Demo.尽管很认真的斟酌,但是水平有限,还请各位批评和斧正. ??Entity Framework Core, 或者 EF Core,是一个方便软件工程师访问数据库的库.有很多方法来构建这样的一个库