选择性地禁用多对多链接表上的级联删除 [英] Selectively Disabling Cascade Delete on Many-to-Many Link Table
问题描述
是否可以在Entity Framework 5 Code First中的自动生成的多对多链接表上选择性删除级联删除选项?这是一个需要它的简单例子:
Is it possible to selectively remove the Cascade Delete option on an automatically-generated many-to-many link table in Entity Framework 5 Code First? Here's a simple example which needs it:
public class Parent
{
public int Id { get; set; }
public virtual IList<ChildA> As { get; set; }
public virtual IList<ChildB> Bs { get; set; }
}
public class ChildA
{
public int Id { get; set; }
[Required]
public virtual Parent Parent { get; set; }
public virtual IList<ChildB> ChildBJoins { get; set; }
}
public class ChildB
{
public int Id { get; set; }
[Required]
public virtual Parent Parent { get; set; }
public virtual IList<ChildA> ChildAJoins { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<ChildA> As { get; set; }
public DbSet<ChildB> Bs { get; set; }
}
当前窗体中的上下文将不适用于数据库,因为级联删除选项在链接表中引入。如果我要创建一个手动链接表,我可以使用Fluent API来配置它的一面,而不是级联,但该选项在多对多关系中是不可用的。
This context in its current form will not apply to a database because of the cascade delete option introduced on the link table. If I were to create a manual link table, I could use the Fluent API to configure one side of it to not cascade, but the option isn't available on a many-to-many relationship.
我知道我可以通过删除 ManyToManyCascadeDeleteConvention
根据这个问题,但这不是我之后 - 我只是希望能够做一个关系,或理想的一个关系的一边。
I'm aware that I can disable Cascade Deletes on all Many-to-Many joins by removing the ManyToManyCascadeDeleteConvention
as per this question, but that's not what I'm after - I just want to be able to do it for one relationship, or ideally one side of one relationsip.
推荐答案
我怀疑在EntityTypeConfiguration映射类中没有办法,但是通过更改DbMigration类中的Up()方法中的代码来实现。
I suspect there is no way to do it in an EntityTypeConfiguration mapping class, but I did it by changing the code in the Up() method in the DbMigration class.
生成的代码链接表是:
CreateTable(
"dbo.ChildBChildAs",
c => new
{
ChildB_Id = c.Int(nullable: false),
ChildA_Id = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.ChildB_Id, t.ChildA_Id })
.ForeignKey("dbo.ChildBs", t => t.ChildB_Id, cascadeDelete: true)
.ForeignKey("dbo.ChildAs", t => t.ChildA_Id, cascadeDelete: true)
.Index(t => t.ChildB_Id)
.Index(t => t.ChildA_Id);
您应该可以通过更改不想级联为false的方式使其正常工作:
You should be able to get it working by changing the side you don't want to cascade to false:
.ForeignKey("dbo.ChildAs", t => t.ChildA_Id, cascadeDelete: false)
如果您可以使用FluentAPI做一次即可使用一对多,但我避风港没有办法找到一种办法。
It would be nice if you could do it using the FluentAPI as you can with one-to-many, but I haven't managed to find a way to do it
这篇关于选择性地禁用多对多链接表上的级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!