问题描述
我想使用代码优先在表上启用级联删除.当模型从头开始重新创建时,即使关系是自动设置的,也不会设置 CASCADE DELETE.奇怪的是,它确实为某些具有多对多关系的表启用了此功能,但您会认为它可能存在问题.
I would like to enable CASCADE DELETE on a table using code-first. When the model is re-created from scratch, there is no CASCADE DELETE set even though the relationships are set-up automatically. The strange thing is that it DOES enable this for some tables with a many to many relationship though, which you would think it might have problems with.
设置:表 A <- 表 B.
Setup:Table A <- Table B.
表 B 的 FK 指向表 A 的 PK.
Table B's FK points to Table A's PK.
为什么这行不通?
推荐答案
你没有得到级联删除的可能原因是你们的关系是可选的.示例:
Possible reason why you don't get cascading delete is that your relationship is optional. Example:
public class Category
{
public int CategoryId { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public Category Category { get; set; }
}
在这个模型中,你会得到一个 Product 表,它有一个 Category 表的外键,但这个键可以为空,并且默认情况下数据库中没有级联删除设置.
In this model you would get a Product table which has a foreign key to the Category table but this key is nullable and there is no cascading delete setup in the database by default.
如果您想拥有所需的关系,那么您有两个选择:
If you want to have the relationship required then you have two options:
注释:
public class Product
{
public int ProductId { get; set; }
[Required]
public Category Category { get; set; }
}
流畅的 API:
modelBuilder.Entity<Product>()
.HasRequired(p => p.Category)
.WithMany();
在这两种情况下,都会自动配置级联删除.
In both cases cascading delete will be configured automatically.
如果你想拥有可选但带有级联删除的关系,你需要明确地配置:
If you want to have the relationship optional but WITH cascading delete you need to configure this explicitely:
modelBuilder.Entity<Product>()
.HasOptional(p => p.Category)
.WithMany()
.WillCascadeOnDelete(true);
在最后一段代码中,您也可以简单地编写.WillCascadeOnDelete()
.此无参数重载默认为 true
以设置级联删除.
In the last code snippet you can also simply write .WillCascadeOnDelete()
. This parameterless overload defaults to true
for setting up cascading delete.
在文档中查看更多相关信息
See more on this in the documentation
这篇关于您如何确保首先对 EF 代码中的表关系启用级联删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!