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.