Cascade Deletion doesn't seem to work for me in EF Core 3

c# cascade entity-framework-core foreign-keys


I have an Entity Framework hybrid project with several related tables.

I have created the Foreign Keys with Cascades on Delete where appropriate both on the database and in the dbcontext but when I run a delete call to the API the related data gets orphaned instead of deleted.

Everything I have read the last couple of days indicates that this should work. I much prefer the database to handle this workload instead of doing them manually in code.

My Foreign Key naming conventions match what is in my dbcontext as does the logic, near as I can tell. The basic structure is that this API stores configurations for running reports. A Report as 1+ Stored Procedure and which have n Parameters. A Stored Procedure record should not exist without a connected Report and each Parameter should likewise not exist without a connected Stored Procedure.

Below is part of the Fluent API for Stored Procedures (Sprocs).

        entity.HasOne(d => d.Report)
            .WithMany(p => p.Sprocs)
            .HasForeignKey(d => d.ReportId)

        entity.HasOne(d => d.ServerInfo)
            .WithMany(p => p.Sprocs)
            .HasForeignKey(d => d.ServerInfoId)

The scripted Foreign Key from SQL Server is as follows:

REFERENCES [dbo].[Reports] ([ID])

We did start this project in Core 2.2 and later upgraded during the project cycle to 3.0 and I realize there were some breaking changes to Cascades but my understanding (which may be flawed) was that the order of operations was the only thing that changed for OnDelete behavior.

None of the cascades are working although I only have a few. I have User => UserGroupXREF so if I delete a given User I need to remove its proprietary Group as well as the relationship mapping in the XREF table. I am pretty sure that will be two calls/steps.

I can't seem to find any indication that I have this set up incorrectly but my Google-Fu has failed me before on word choice for searches.

Thank you for your help.

4/16/2020 12:18:19 PM

Accepted Answer

Your Foreign Key constraint is set to NOCHECK. This is preventing the Foreign Key from being enforced which in turn is resulting in the DELETE CASCADE not occurring.

You can re-enable your constraint by running the following command:

ALTER TABLE [dbo].[Sprocs] CHECK CONSTRAINT [FK_Sprocs_Reports]

4/16/2020 3:56:40 PM

Related Questions


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