2

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?

Keegan Kozler
  • 361
  • 1
  • 3
  • 9
  • Does this answer your question? [Equivalent for .HasOptional in Entity Framework Core 1 (EF7)](https://stackoverflow.com/questions/35562483/equivalent-for-hasoptional-in-entity-framework-core-1-ef7) – Rafael Herscovici Nov 20 '21 at 22:32
  • I don't think so, but thanks! The only difference from my original configuration is the `IsRequired` call, but removing that doesn't fix my issue. – Keegan Kozler Nov 21 '21 at 03:44
  • Not possible, because of the relational databases FK constraint rules - all composite FK columns must be null or not null. There is nothing EF Core can do as it is database restriction. – Ivan Stoev Nov 21 '21 at 14:28
  • I don't think that's right. In SQL, I can create an optional foreign key that references two columns, one nullable and the other non-nullable. – Keegan Kozler Nov 23 '21 at 18:31

0 Answers0