Delete a list of data in EF

1

I have a method that deletes a version of a file according to the last file version, 1 file can have many versions, and I wanted to delete all versions, I was able to delete only 1 version of a particular file. 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 erases only 1 version of the requested file, how would it be to erase all versions of the same GUID_FILE?

    
asked by anonymous 11.02.2015 / 13:56

2 answers

1

Hello,

The way you did it will only delete 1 Record (FirstOrDefault) where the .GUID_RANGE == file_Version.GUID_RANGE

To delete all, do something like this

I did out of 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();
    }
}
    
11.02.2015 / 14:02
1

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

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();
}  

In EF6 it's simpler:

using (var ctx = new TESTEntities())
{
    ctx.ARQUIVO_VERSAO.RemoveRange(arquivo.ARQUIVO_VERSAO);
    ctx.SaveChanges();
}  
    
11.02.2015 / 14:41