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; }
}
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.
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.
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.
The code generated for the link table is:
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);
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)
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
来源:https://stackoverflow.com/questions/13726014/selectively-disabling-cascade-delete-on-many-to-many-link-table