Cascade delete in table per type(TPT) EF Core 5

Viewed 385

I have two entities employee manager and I am using ef core 5.

public class Employee
{
        public long Id{ get; private set; }
        public string FirstName { get; private set; }
        public string LastName { get; private set; }
}

public class Manager : Employee
{
        public long StoreId{ get; private set; }
}

I am using type per table, using fluent api

class EmployeeConfiguration : IEntityTypeConfiguration<Employee>
    {

        public void Configure(EntityTypeBuilder<Employee> builder)
        {
            builder.ToTable("Employee");
            builder.HasKey(x => x.Id);    

        }
    }

class ManagerConfiguration : IEntityTypeConfiguration<Manager>
    {

        public void Configure(EntityTypeBuilder<Manager> builder)
        {
            builder.ToTable("Manager");
        }
    }

As a result I have two tables. The problem is, i want a cascade on delete behavior, when I remove the employee , I want to remove and the record of the manager table. But the default behavior is not this. When i try to delete the parent record I have a fk violation

How i can configure the OnDelete in a table per type case?

EDIT EF core understand the relationship and after the migration generate

b.HasOne(".......Employee", null)
                        .WithOne()
                        .HasForeignKey("....Manager", "Id")
                        .OnDelete(DeleteBehavior.ClientCascade)
                        .IsRequired();
1 Answers

I know this is old. But here is how I did it in case anyone is looking.

modelBuilder.Entity<Manager>(entity =>
{
    entity.ToTable("Manager")
        .HasOne<Employee>()
        .WithOne()
        .HasForeignKey<Manager>(x => x.Id)
        .OnDelete(DeleteBehavior.Cascade);
});
Related