Why is it that when I delete or edit the record from table x it is also removed from table y?

Asked

Viewed 56 times

5

I have a system in ASP MVC with C# using Entity framework.

I have the table Pedidos and Agenda.

On the table agenda I have a column with the id of the request.

When the order is canceled, I have to remove from the table Agenda to release a schedule for a new order.

The problem is that when you remove the row from the table Agenda with request 13(for example), in the table pedido the same is removed also.

I already did a search and found something on Cascade in the SQL, but it’s not activated.

What can it be?

Follows code:

 public partial class ifixEntities : DbContext
{
    public MyEntities()
      : base("name=MyEntities")
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        modelBuilder.Entity<Agenda>().HasOptional<Pedido>(s => s.Pedido).WithMany().WillCascadeOnDelete(false);                        
    }
}

2 answers

4


It’s called Cascade Delete and is a standard behavior of the Entity Framework.

You can also put some general rules, and not just specific for each model.

Ex:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()
}

So you remove on all models.

  • Thanks, just confirming: this way is deleted only from 1 table?

  • 1

    But this behavior makes Entity do because he thinks the other record will be orphaned, so make sure you really need to keep the other data, of course he just 'thinks' you should decide.

  • 1

    Ok, thank you very much!! yes I need it removed only from 1 table, to keep order history in the system.

2

example to remove Cascade delete

public class SchoolContext<: DbContext
{
    public SchoolContext():base("MySchool")
    {
                }

    public DbSet<Student> Students { get; set; }
    public DbSet<Standard> Standards { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
            .HasOptional<Standard>(s => s.Standard)
            .WithMany()
            .WillCascadeOnDelete(false);
    }
}

source: http://www.entityframeworktutorial.net/code-first/cascade-delete-in-code-first.aspx

  • Srs, just informing I tried to use the two settings but it continues to be removed from both tables.

  • @Ronaldoperes puts his code there in the question

Browser other questions tagged

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