Entity delete table and its relationships

0

Is there any way to delete a table record and all of its relationships at once? because I currently delete each related record before deleting the main record, and this takes a lot of time, for example I have the table Note and I want to delete a record of it, but before I need to delete a record in the table ItemNote that is related to the table Note, so only after deleting the table record Note, is there any good way to do this?

    
asked by anonymous 02.10.2017 / 21:34

1 answer

1

What you need is to turn on cascading. I think you're doing something like this:

Nota.ItemsNotas.Clear();
Context.Entry(Nota).State = EntityState.Deleted;
Context.SaveChanges();

The Entity Framework (6) automatically uses some conventions for cascading deletion. Usually these conventions are taken away for the programmer to add where he wants it to occur:

//Não vai permitir que campos REQUIRED sofra Cascade Delete.
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

Removing these conventions is interesting because it is not always that you want Cascade DELETE to occur.

To activate it in just one relationship (in your case Note and ItemNote) you need to set up Notes for:

HasMany(e => e.ItemNotas)
    .WithRequired(e => e.Nota)
    .HasForeignKey(e => e.NotaId)
    .WillCascadeOnDelete(true);

03.10.2017 / 15:55