Kenath Perera
Kenath Perera

Reputation: 3

Why my Delete Cascade policy is not working Properly

I have 2 tables called Domain and Domain Theme. it has one to one relationship. Here the 2 model classes.

public class Domain
    {
        
        public int OrganizationDomainId { get; set; }
        [MaxLength(200), Required]
        public string Domain { get; set; }
        public bool Active { get; set; }
        public int? ThemeId { get; set; }
        [ForeignKey("ThemeId")]
        public virtual OrganizationDomainTheme OrganizationDomainTheme {get;set;}

    }
public class OrganizationDomainTheme
    {
        public int OrganizationDomainThemeId { get; set; }
        public string PrimaryColor{get;set;}
        public virtual OrganizationDomain OrganizationDomain { get; set; }
        
    }

I have implemented a delete behavior by using model builder for my 2 tables.

  1. Set Domain Null when i delete a Theme. (this is working fine)
modelBuilder.Entity<OrganizationDomainTheme>()
                .HasOne(odt => odt.OrganizationDomain)
                .WithOne(od => od.OrganizationDomainTheme)
                .OnDelete(DeleteBehavior.SetNull);
  1. Delete Domain Should delete the Theme.(This is not working as expected)
modelBuilder.Entity<OrganizationDomain>()
                .HasOne(od => od.OrganizationDomainTheme)
                .WithOne(odt=>odt.OrganizationDomain)
                .OnDelete(DeleteBehavior.Cascade);

Senario.

When i delete a Theme it sets the Domain Null as i expected from number 1.

But When i delete a Domain it will not delete the Theme. Theme is still on the table.

Am i configure it wrong ? Please Help.

I want to delete the theme that belong to the domain when i delete a domain.

Upvotes: 0

Views: 48

Answers (1)

Qiang Fu
Qiang Fu

Reputation: 8811

In one-to-one relationship, the entity with foreignkey is "dependent entity" (Domian). The other is " principal entity" (Theme).
All the Deletebehaviour only take effect on dependent entity when you delete principal eneity. https://entityframeworkcore.com/saving-data-cascade-delete
AFAIK, you have to delete that principal entity manually after delete the denpendent entity.

Upvotes: 1

Related Questions