Let's say I have two tables: Superhero
and Universe
.
Superhero
has a composite primary key, since Loki's introduced us to variants, modeled in EF Core like so:
modelBuilder.Entity<Superhero>()
.HasKey(o => new { o.Id, o.UniverseId });
Some superheroes have hero parents, so I need Superhero
to have a self-referencing foreign key, which is not required:
modelBuilder.Entity<Superhero>()
.HasOne(o => o.ParentHero)
.WithMany(o => o.ChildHeroes)
.HasForeignKey(o => new { o.ParentId, o.UniverseId })
.IsRequired(false);
I don't want cascade on delete for this relationship; instead, I'd like to set the children's ParentId
column to null
, while the UniverseId
column remains unchanged. I thought I could accomplish this by using the DeleteBehavior.SetNull
option:
modelBuilder.Entity<Superhero>()
.HasOne(o => o.ParentHero)
.WithMany(o => o.ChildHeroes)
.HasForeignKey(o => new { o.ParentId, o.UniverseId })
.OnDelete(DeleteBehavior.SetNull)
.IsRequired(false)
;
But that doesn't work as I expected. When I remove the parent hero, like so:
DbContext.Superhero.Remove(parentHero);
I get the following error:
System.InvalidOperationException: The association between entity types 'Universe' and 'Superhero' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.
Is there any way I can get around this situation?