Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Disabling Cascade Deletes - EF Core

RSS
Modified on Thu, Nov 19, 2020, 10:53 AM by Administrator Categorized as 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
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2020, Patrick Jasinski.