Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFrameworkCore: DeleteBehavior too many options [closed]

Setting up the builder parameter inside the OnModelCreating method in my app DbContext I found many options in OnDelete/DeleteBehavior: Cascade, ClientCascade, ClientNoAction, ClientSetNull, NoAction, Restrict and SetNull.

enter image description here

Searching on the web I found some content about some of them, but not about them all. What are the differences about them?

like image 936
Sérgio Damasceno Avatar asked Jan 26 '26 11:01

Sérgio Damasceno


2 Answers

Most of the active ones can be referred from here and a more nourished documentation here.

  • Cascade is literally what it means, child and dependants are dropped.
  • ClientCascade basically drops dependant entities as well.
  • ClientNoAction basically does nothing to any foreign keys, they are intact even after deletion. Not recommended by Microsoft.
  • NoAction is basically nothing, the entity itself is the only one affected.
  • Restrict is the same as NoAction
  • SetNull basically sets relationship keys to null
like image 80
Nicholas Avatar answered Jan 29 '26 09:01

Nicholas


The main differences are related to how the corresponding records in the database and the local model will change. The main thing is to pay attention to whether the navigation property is added to the local data context or not.

Cascade (default for the required relationship)

Deletes related records even if they are not added to the local context

ClientCascade

Deletes related records, but only those that have been added to the local context

SetNull

Set the associated foreign key property/column to null, even if it is not added to the local context.

NotAction, Restrict and ClientSetNull (default for optional relationships)

Sets the corresponding foreign key column/property to null only if the related entity is added to the local context. In the documentation, NotAction, Restrict, and ClientSetNull have the same description. When you try to test these parameters, they will work the same way. I assume that these parameters can create different tables in SQL. However, for MS SQL, they are the same (for DeleteBehavior.Restrict creates "ON DELETE NO ACTION", but this is the default configuration for MS SQL). Nevertheless, from the Entity Framework's point of view, the principle of operation should not change for any SQL dialect.

ClientNoAction.

This parameter does not affect the database either with or without related entities in the local context.

Documentation: https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.deletebehavior?view=efcore-8.0

like image 21
DmytroHoliaka Avatar answered Jan 29 '26 10:01

DmytroHoliaka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!