Disabling Cascade Deletes - EF Core

Overview

By default EF Core 3 creates foreign keys with delete cascading enabled. This article provides code to turn this off.

Reusable Code

private void DisableCascadeDeletes(ModelBuilder mb)
{
    var types = mb.Model.GetEntityTypes();

    foreach (var type in types)
    {
        var fkeys = type.GetForeignKeys();

        foreach (var fk in fkeys)
        {
            if (!fk.IsOwnership)
            {
                fk.DeleteBehavior = DeleteBehavior.Restrict;
            }
        }
    }
}

Usage

Within your data model class, include this line of code.
override void OnModelCreating(ModelBuilder mb)
{
    // Add the next line to your code
    DisableCascadeDeletes(mb);

    // your other code goes here
}