Entity delete table and your relationships

Asked

Viewed 729 times

0

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

  • 2

    Behold if this answer is what you are looking for. If it is not, try to explain a little more your problem so that we can help you.

  • which is the database, this has to be done in the database and set up in the ORM to let him know, despite what this is in the responsibility of the database is the best way if you want to delete the record cascade.

  • We use SQL Server

1 answer

1


What you need is to activate the cascade exclusion. I believe you are doing something like this:

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

Entity Framework (6) automatically uses some conventions for cascading exclusion. Usually these conventions are removed so that the programmer adds 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 to occur Cascade DELETE.

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

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

Remember that there is only this convention for Fluentapi, there is by default a way to do by Data Annotation.

If you use Migration, just run Migration and update your database and it will generate something like:

.ForeignKey("dbo.Nota", t => t.NotaId, cascadeDelete: true)

Otherwise, it is necessary to make the alter table also for it to work:

ALTER TABLE "TABELA" MODIFY CONSTRAINT ... ON DELETE CASCADE;

There you change the names according to your tables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.