1

I am using Entity Framework 6.0.1 Code-First approach and I am working on the removal of my objects from the database.

I have set the Delete on Cascade rule as true for the 0..1-N relationships:

HasRequired(i => i.OneEntity).WithMany(v => v.ManyEntities).
    WillCascadeOnDelete(true);

Now, inside my removal methods, I do the following:

For 1-N relationships, I remove from the context the relative objects:

//OneEntity is an entity that contains a list of referenced entities
//of another type.
RootEntity.OneEntity.ManyEntities.ForEach(be  => ctx.OtherElements.Remove(be));

For 0..1-1 relationships, I remove the element from the list of the object, if optional (on required, the EF conventions specify that cascading is applied automatically (older question)):

//One entity is a reference to another entity of another type of  
//RootEntity.
ctx.OneEntities.Remove(RootEntity.OneEntity);

And for N-N relationships, I clean the list of the object:

//No context removal operation here.
RootEntity.ManyToManyEntities.Clear();

Now, while this works, I have the feeling I am doing things wrong or applying unnecessary operations in terms of the best handling.

My first thoughts for refactoring are:

1) Remove any context removal code from the 1-N relationships, as cascading might do the job.

2) Apply cascading on the optional 1-1 Relationships.

3) Remove any list clearance for the N-N Relationships, as this should be done automatically.

Should I proceed with those thoughts, or is the whole code OK for this kind of handling? Is there any better alternative strategy for the objects removal? My drawbacks are that cascading might cause unwanted side effects and that depends on what the database used supports.

Community
  • 1
  • 1
Nick Louloudakis
  • 5,856
  • 4
  • 41
  • 54

1 Answers1

1

If you have the proper relations configured in your database the cascade delete will happen automatically - sql will do it itself. Therefore the child entities will not be there after that moment and you will have nothing to delete if you try it with another request.

I use EF 6 'code first' with proper relations defined and I use only one delete of the parent - everything else is removed automatically. The rules for the parent-child relations are built in the database schema and SQL server does the job and we can consider this safe.

Ognyan Dimitrov
  • 6,026
  • 1
  • 48
  • 70