c# - Entity Framework Core Cascade Delete on One-To-One Relationship

c# cascade entity-framework entity-framework-core one-to-one

Question

I have a one-to-one relationship between Service and Lexikon while the Service has a foreign key to Lexikon. My Service doesn't need a Lexikon so I made the LexikonID nullable. But my Lexikon can only exist if it is related to a Service so I made the navigation property [required]. I'm using Code First so EF builds my Database.

 public class Service
 {

    public int ServiceID { get; set; }

    //Foreignkey
    public int? LexikonID { get; set; }

    //Navigation Properties

    public Lexikon Lexikon { get; set; }
 }

 public class Lexikon
 {
    public int LexikonID { get; set; }

    //Navigation Properties
    [Required]
    public SoftwareService SoftwareService { get; set; }

 }

I'm trying to delete the data automatically in table Lexikon if i delete my Service but unfortunately I'm not sure how to do this since I'm new to EF.

I tried this code in dbContext:

       modelBuilder.Entity<SoftwareService>()
                .HasOne(l => l.Lexikon)
                .WithOne(s => s.SoftwareService)
                .HasForeignKey<SoftwareService>(l => l.LexikonID)
                .OnDelete(DeleteBehavior.Cascade);

but when I delete my Service the data in table Lexikon will still be in it. On the other hand when I delete the lexikon it will automatically delete the Service which is nice but I also want it to be happen to my Lexikon when I delete my Service.

Unfortunately I'm not familiar with the OnDelete-Method so I hope someone can help me.

1
2
8/31/2017 10:06:22 AM

Popular Answer

Did you generate the database from your model? You have to, because EF generates an ON DELETE CASCADE constraint. Otherwise, you will need to add it by hand. I wrote a post on this problem, for EF pre-Core, but it still applies: https://weblogs.asp.net/ricardoperes/entity-framework-pitfalls-cascade-deletes.

1
8/31/2017 10:09:31 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow