How to delete data from one table related to another

Asked

Viewed 111 times

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 to delete, as would be this method in EF to delete with all files linked to the directory?

  • In case of relationships between entities, delete must be by cascade.

  • And then how would you look in my case Using EF?

1 answer

2


In your entity classes, in the navigation objects, just 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 mapping with Entitytypeconfiguration, you can use Willcascadeondelete:

HasRequired(t => t.Categoria)
  .WithMany(m => m.Produtos)
  .HasForeignKey(d => d.id)
  .WillCascadeOnDelete(true);
  • in my template layer? in case I would paste [Required] in my List<File> Archivist ?

  • It depends a lot on how your application was implemented, if Voce has used Data Annotations this is an option, more if you have used maps with Entitytypeconfiguration, you can do this in the mapping, using Willcascadeondelete

  • I use a extending class of Dbcontext, with the Dbset methods:

  • public Dbset<DIRECTORY> DIRECTORY { get; set; }

  • This Dbset object is the mapping object within the context (Dbcontext). If you use Data Annotations you have to include the attributes within your DIRECTORY class, or in the FILES class. Take a look at the use of Data Annotations on the link http://www.entityframeworktutorial.net/code-first/dataannotation-in-code-first.aspx. the second option that I give you is for the use of mapping with Fluentapi, take a look at the http link://www.entityframeworktutorial.net/code-first/Fluent-api-in-code-first.aspx

  • the Architect here of the project said he would see this context later and that I did not need to implement it now, anyway his response was of great help.

Show 1 more comment

Browser other questions tagged

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