Delete Cascade with Entity framework

Asked

Viewed 814 times

0

I have the following situation: my database is Mysql, when I try to delete a record directly in the database, from this message:

Cannot delete or update a parent row: a foreign key constraint fails (`lifeproject`.`t0041_usuario`, CONSTRAINT `fk_t0041_usuario_t0040_grupo_usuario1` FOREIGN KEY (`t0040_id_grupo`) REFERENCES `t0040_grupo_usuario` (`t0040_id_grupo`) ON UPDATE CASCADE)

ok, this is correct, this is exactly what I need, however, when I try to delete by the application, it is not respected the On Delete restrict, which is set in the table creation. I am using Entity Framewrok 6. I understand that when trying to delete by the application, Mysql should trigger the same restriction exception for the application. Someone can help me?

here is the group class

[Table("t0040_grupo_usuario")]
public class GrupoUsuarioModel
{
    #region propriedades
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public string t0040_id_grupo { get; set; }

    [Required]              
    public string  t0040_descricao { get; set; }

    [Required]
    public int t0020_id_empresa { get; set; }

    [ForeignKey("t0020_id_empresa")]
    public virtual EmpresaModel EmpresaModel { get; set; }


    public virtual ICollection<UsuarioModel> UsuarioModel { get; set; }        
    public virtual ICollection<AcessoModel> AcessoModel { get; set; }
    #endregion
}

}

here is the user class

 [Table("t0041_usuario")]
public class UsuarioModel
{
    #region propriedades       
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int t0041_id_usuario { get; set; }

    [Required]
    public string t0041_nome_usuario { get; set; }

    [Required]        
    public string t0040_id_grupo { get; set; }       

    [Required]
    public string t0041_descricao { get; set; }

    [Required]
    public string t0041_senha { get; set; }

    [Required]
    public int t0020_id_empresa { get; set; }

    [ForeignKey("t0020_id_empresa")]
    public virtual EmpresaModel EmpresaModel { get; set; }

    [ForeignKey("t0040_id_grupo")]
    public virtual GrupoUsuarioModel GrupoUsuarioModel { get; set; }
    #endregion
}
  • I didn’t understand. By Mysql he gives you the message, but by the system (EF) no?

  • That’s right, the system(EF) does not give the message and erases the record and its dependencies

  • I needed this information to better understand your problem. I hope the answer helps you.

1 answer

1

Entity Framework uses some conventions in its structure. The Cascade Delete is one of them.

There are some ways to remove this convention. The first, and simplest, is in the context itself DbContext, where you can add the following code:

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

In this way, we are talking to remove the convention of Cascade Delete in the relationships of Onetomany, or 1:N.

There are other options, such as ManyToManyCascadeDeleteConvention, for example.

Another way, if you’re using Fluent Api of the Enfity Framework, is to make the annotation in the configuration file, this way:

modelBuilder.Entity<>(GrupoUsuarioModel)
            .HasOptional(p => p.UsuarioModel)
            .WithMany()
            .WillCascadeOnDelete(false);//true para adicionar

Remembering that if you use this way, you must perform the configuration in each map.

This article explains a little more about this, including the option in the database (Sql Server).

Another point worth mentioning is that there are several conventions, such as the PluralizingTableNameConvention, which is responsible for "pluralizing" the table name, usually by adding the suffix es in the tables.

See the full list in the official documentation.

Browser other questions tagged

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