在多对多链接表上有选择地禁用级联删除

时间:2012-12-05 14:58:26

标签: entity-framework ef-code-first entity-framework-5

是否可以在Entity Framework 5 Code First中自动生成的多对多链接表中有选择地删除级联删除选项?这是一个需要它的简单示例:

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 question移除ManyToManyCascadeDeleteConvention来禁用所有多对多连接上的级联删除,但这不是我想要的 - 我只是想能够为一种关系做到这一点,或者理想情况下是一个关系的一面。

1 个答案:

答案 0 :(得分:0)

我怀疑在EntityTypeConfiguration映射类中无法做到这一点,但我是通过更改DbMigration类中Up()方法中的代码来实现的。

为链接表生成的代码是:

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的那一方来使它工作:

    .ForeignKey("dbo.ChildAs", t => t.ChildA_Id, cascadeDelete: false)

如果你能用一对多的FluentAPI做到这一点会很好,但我还没有找到办法做到这一点

相关问题