Entity Framework auto relationship enable cascading delete

Asked

Viewed 875 times

4

How to create a cascading deletion, in a self-relationship using the fluent api and enable this in entity framework?

Code:

 Public class Usuario {

    public int UsuarioID { get; set; }
    public int? ObjPaiID { get; set; }
    public virtual Usuario ObjPai { get; set; }
    public virtual IList<Usuario> ListaPartes { get; set; }
}

Context:

//Auto-relacionamento Projeto
   modelBuilder.Entity<Usuario>()
   .HasOptional(p => p.ObjPai)
   .WithMany(p => p.ListaPartes)
   .HasForeignKey(p => p.ObjPaiID);
  • I believe that if you enable in the bank, and give an update on the Entity Model, it already happens.

  • Solved the problem?

  • No friend, I chose to do otherwise. I had to sweep the list of the children of the object and delete them through a loop.

1 answer

4

You can use the .WillCascadeOnDelete();

Example:

//Auto-relacionamento Projeto
   modelBuilder.Entity<Usuario>()
   .HasOptional(p => p.ObjPai)
   .WithMany(p => p.ListaPartes)
   .HasForeignKey(p => p.ObjPaiID)
   .WillCascadeOnDelete(true);

Browser other questions tagged

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