博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
EF里一对一、一对多、多对多关系的配置和级联删除
阅读量:4981 次
发布时间:2019-06-12

本文共 2233 字,大约阅读时间需要 7 分钟。

This is exactly how cascading deletes behaves in EF. Setting Cascade on a relation in EF designer instructs EF to execute DELETE statement for each loaded realated entity. It doesn't say anything about ON CASCADE DELETE in the database.

Setting Cascade deletion when using EF needs two steps:

  • Set Cascade on relation in EF designer. This instruct context that all loaded related entitiesmust be deleted prior to deletion of the parent entity. If this doesn't happen EF will throw exception because internal state will detect that loaded childs are not related to any existing parent entity even the relation is required. I'm not sure if this happens before execution of delete statement of the parent entity or after but there is no difference. EF doesn't reload related entities after executing modifications so it simply doesn't know about cascade deletes triggered in the database.
  • Set ON CASCADE DELETE on relation in database. This will instruct SQL to delete all related records which were not loaded to context in the time of deleting the parent.

The implementation of cascade deletes in EF is strange and quite inefficient but this is how it behaves and if you want to use it, you must modify your application to behaves correctly in this scenario.

----------------------------------------------------------------

You can configure cascade delete on a relationship by using the WillCascadeOnDelete method. If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.

You can remove these cascade delete conventions by using:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()

modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()

The following code configures the relationship to be required and then disables cascade delete.

modelBuilder.Entity
()     .HasRequired(t => t.Department)     .WithMany(t => t.Courses)     .HasForeignKey(d => d.DepartmentID)     .WillCascadeOnDelete(false);

 

参考

转载于:https://www.cnblogs.com/HQFZ/p/4519848.html

你可能感兴趣的文章
线段树做题总结
查看>>
JAVA基于File的基本的增删改查
查看>>
RocketMQ安装与实例
查看>>
PHP知识库图谱汇总(完善中)
查看>>
大道至简阅读笔记07
查看>>
爬山 启发式合并 / STL
查看>>
[HNOI2004]宠物收养所 题解
查看>>
Nexus3.x帐号权限配置
查看>>
简易版时间封装
查看>>
抖音怎么才能发长视频?详谈抖音发长视频(60s)的要求
查看>>
c#中ObservableCollection<T>排序方法
查看>>
Vue.Js
查看>>
炫酷的手风琴效果
查看>>
面试官:你是如何使用JDK来实现自己的缓存(支持高并发)?
查看>>
iOS开发 代码 或 <Home+Power>截屏
查看>>
字符编码大纲
查看>>
使Python中的turtle模块画图两只小羊
查看>>
阿里云数据库Redis版 ERR invalid password
查看>>
z-index坑
查看>>
javascript基础学习五-原型prototype
查看>>