I am learning C# and how to use Entity Framework. I believe that I know what is Cascade, Restrict, NoAction and SetNull behaviors.
But there are other behaviors with the prefix Client:
I would like to understand what are the difference between them and when should I use ClientCascade instead of Cascade or ClientNoAction instead of NoAction.
2
Answers
the short answer is– when
dependent/ref. entities
areloaded/cached
in memory, thecascade delete
actionfails
on the main entity – because aCYCLIC ref. LOCK
.ClientCascade
allows theDBContext
to delete entities even if there is aCYCLIC ref. LOCK
The Context deletes the entities it tracks, when we delete the parent.
Cascade option creates a migration script with
ON DELETE CASCADE
, whileClientCascade
creates a migration script withON DELETE NO ACTION
.Cascade is the default behavior, when using the required relationship i.e
Foreign key
is Not NullableUntracked entities if any are deleted if the
ON DELETE CASCADE
is setup in the database. If not results in aFOREIGN KEY violation
.Not all databases support Cascade or does not support fully. Especially if there are cycles in relationships. Use
ClientCascade
and load all related entities before deleting the parent. The context will perform the Cascade Delete on the client-side.also read:
https://learn.microsoft.com/en-us/ef/core/saving/cascade-delete