Batch deletion using Linq

1

I have a table, which is used in my Model.edmx , with the following fields:

ID
ID_PROJETO
ID_ITEM
VALOR

How to convert the SQL below into a Linq expression?

DELETE FROM TB_RECEITA WHERE ID_PROJETO = 100 AND ID_ITEM = 5
    
asked by anonymous 05.01.2015 / 21:03

2 answers

1

There is the DeleteAllOnSubmit method. I've never used this method, but it looks something like this:

var receitas = (from r in contexto.Receitas
   where r.ProjetoId == 100 && r.ItemId == 5
   select r).ToList();

contexto.Receitas.DeleteAllOnSubmit(receitas);
contexto.SubmitChanges();

For those who do not use Linq (extension methods only), the manual code below is a solution:

foreach (var objeto in contexto.Receitas.Where(r => r.ProjetoId == 100 && r.ItemId == 5))
{
    contexto.Receitas.DeleteObject(objeto);
}

contexto.SaveChanges();

You can also implement an extension as follows:

public static class EntityFrameworkExtensions
{
    public static void DeleteAllObjects<TEntity>(this ObjectSet<TEntity> dbset, IEnumerable<TEntity> data) where TEntity : class {
        foreach (var objeto in data.ToList()) 
            dbset.DeleteObject(objeto);
    }
}

Usage:

contexto.Receitas.DeleteAllObjects(contexto.Receitas.Where(r => r.ProjetoId == 100 && r.ItemId == 5));
contexto.SaveChanges();
    
05.01.2015 / 21:33
0

Here's an example:

using (Entities conexaoEF = new Entities())
{
     // 1 - Seleciona a entidade no banco a qual se quer apagar. 'receitaParaDeletar'
     var receitaParaDeletar = conexaoEF.TB_RECEITA.Single(c => c.ID_PROJETO == 100 && c.ID_ITEM = 5);

     // 2 - Passa a entidade atraves do metodo 'Remove' dentro do contexto do seu Edmx.
     conexaoEF.TB_RECEITA.Remove(receitaParaDeletar);

     // 3 - Efetua as alterações.
     conexaoEF.SaveChanges();
 }
    
05.01.2015 / 22:02