John Mathison
John Mathison

Reputation: 914

Entity Framework Code first cycles or multiple cascade paths

We have a database that is creating some multiple cascade paths errors. I do understand what that means and what is happening, but I'd like to know the best approach since we have to remove some of the OnDelete Cascade options we have.

This is our table structure:

SCHOOL
- SchoolId  
- Name
- ....

STUDENT
- StudentId
- SchoolId
- Name
- ...

COURSE
- CourseId
- SchoolId
- Name

STUDENT-COURSE
- StudentId
- CourseId
- ....

So here we have the cycle, because when deleting a school the entity Student-Course is going to be deleted from 2 different sides, creating the cycle.

I understand what happens here:

HasMany(p => p.Students)
   .WithRequired(p => p.School)
   .HasForeignKey(p => p.SchoolId)
   .WillCascadeOnDelete(true);  

And I know I can do:

HasMany(p => p.Students)
    .WithRequired(p => p.School)
    .HasForeignKey(p => p.SchoolId)
    .WillCascadeOnDelete(false); 

The question here is what would be the best approach.

Thanks.

Upvotes: 0

Views: 172

Answers (1)

Andrei Filimon
Andrei Filimon

Reputation: 1188

I would remove on delete cascade from the School, and leave the others as is, and when deleting a school add some logic to delete related students, courses (but his keeps a consistency for deletes in lower levels). If you remove on delete cascade from the Students, you will need to manually add deletion logic for them to clean related student courses first, and will be somehow inconsistent with courses delete (hierarchical level is not consistent in terms of deletion logic).

Upvotes: 1

Related Questions