Disable cascade delete on EF Core 2 globally

entity-framework entity-framework-core

Question

I need to know about ways of disabling cascade delete in EF Core 2 globally. Any help is appricated.

In EF 6.x we used following code to disable cascade delete on both OneToMany and ManyToMany realtions:

builder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
builder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
1
27
10/2/2017 1:15:11 PM

Accepted Answer

Unfortunately EF Core currently (latest at this time v2.0) does not expose a good way to control the conventions globally.

The default EF Core 2.0 convention is to use DeleteBehavior.Cascade for required and DeleteBehavior.ClientSetNull for optional relationships. What I can suggest as workaround is a typical metadata model loop at the end of the OnModelCreating override. In this case, locating all the already discovered relationships and modifying them accordingly:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // ...

    var cascadeFKs = modelBuilder.Model.GetEntityTypes()
        .SelectMany(t => t.GetForeignKeys())
        .Where(fk => !fk.IsOwnership && fk.DeleteBehavior == DeleteBehavior.Cascade);

    foreach (var fk in cascadeFKs)
        fk.DeleteBehavior = DeleteBehavior.Restrict;

    base.OnModelCreating(modelBuilder);
}
55
8/15/2018 2:30:54 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow