How to delete data from a table related to another

0

I have the following situation with a method of deleting directory:

internal void DeleteDiretorio(Model.Diretorio diretorio)
    {
        using (var ctx = new TESTEntities())
        {
            var dir = ctx.DIRETORIO.FirstOrDefault(a => a.DIRETORIO_GUID == diretorio.DIRETORIO_GUID);
            if (dir == null)
                throw new ArquivoException("Diretorio não encontrado");
            ctx.Entry(dir).State = System.Data.EntityState.Deleted;
            ctx.SaveChanges();

        }

    }

This method is to delete according to the id, but directory it has a list of files so it does not allow deletion, how would this method in EF to delete with all files linked to the directory?

    
asked by anonymous 10.02.2015 / 14:42

1 answer

2

In your entity classes, in navigation objects, simply use Data Annotation [Required] , as in the example below:

public class Produto
{
    public int Id { get; set; }
    public string Nome { get; set; }

    [Required]
    public Categoria Categoria { get; set; }
}

If you are using mappings with the EntityTypeConfiguration, you can use WillCascadeOnDelete:

HasRequired(t => t.Categoria)
  .WithMany(m => m.Produtos)
  .HasForeignKey(d => d.id)
  .WillCascadeOnDelete(true);
    
10.02.2015 / 14:53