Delete a data list in the EF

Asked

Viewed 297 times

1

I have a method that deletes a version of a file according to the version of the file passed, 1 file may have many versions, and I wanted to delete all versions, I managed to delete only 1 version of a particular file. But I want to delete all versions of a particular file, see:

internal void ApagarArquivoVersao(Model.ArquivoVersao arquivoVersao)
    {
        using (var ctx = new TESTEntities())
        {
            var fileVer = ctx.ARQUIVO_VERSAO.FirstOrDefault(a => a.ARQUIVO_GUID == arquivoVersao.ARQUIVO_GUID);
            if (fileVer == null)
                throw new ArquivoException("Arquivo não encontrado");

            ctx.Entry(fileVer).State = System.Data.EntityState.Deleted;
            ctx.SaveChanges();
        }
    }

The above method deletes only 1 version of the requested file, as it would look to erase all versions of the same ARQUIVO_GUID?

  • What version of EF are you using? if it is EF6 you can use the method . Removerange()

2 answers

1


Hello,

The mode you made will only delete 1 Record (Firstordefault) where a.ARQUIVO_GUID == fileVersao.ARQUIVO_GUID

To erase them all, do something like this

I did outside the visual studio, there may be syntax errors

internal void ApagarArquivoVersao(Model.ArquivoVersao arquivoVersao)
    {
        using (var ctx = new TESTEntities())
        {
            var arquivos = ctx.ARQUIVO_VERSAO.Where(a => a.ARQUIVO_GUID == arquivoVersao.ARQUIVO_GUID).ToArray();

            if (arquivos.Length == 0)
                throw new ArquivoException("Arquivo não encontrado");

            foreach(ARQUIVO_VERSAO fileVer in arquivos){
                ctx.Entry(fileVer).State = System.Data.EntityState.Deleted;
            }
         ctx.SaveChanges();
    }
}
  • I was trying with Where, but it wasn’t working because I had to convert to array, thanks.

1

If you want to delete all versions of a file, then it is interesting to have the file as a method parameter.

internal void ApagarVersoes(Model.Arquivo arquivo)

As for the method, if you are using EF5, you can do the following:

using (var ctx = new TESTEntities())
{
    foreach (var versao in arquivo.ARQUIVO_VERSAO)
    {
        ctx.ARQUIVO_VERSAO.Remove(versao);
    }
    ctx.SaveChanges();
}  

EF6 is simpler:

using (var ctx = new TESTEntities())
{
    ctx.ARQUIVO_VERSAO.RemoveRange(arquivo.ARQUIVO_VERSAO);
    ctx.SaveChanges();
}  

Browser other questions tagged

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