Hyston blog
About • Archive • RSS

Cascade delete nullable

April 17, 2019

On entity framework on deletion one-to-many it is possible to cascade delete entities. However, if foreignKey is nullable, this relation should be set to null, and EF does it automatically with one small catch: only if entity is in memory.
If it is doesnt loaded, then it will throw ugly error The DELETE statement conflicted with the REFERENCE constraint. To avoid that, load entity implicitly by any possible method like Include() or using Queryable.Load like that: Context.Entry(parentEntry).Collection(p => p.SubItems).Load();
here We load all SubItems, that have a foreign key to ParentEntry and, when we delete it later, all those keys sets to null automatically. More about this here


Next entry → ← Prev entry