Batch deletion using Linq

Asked

Viewed 104 times

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

2 answers

1


There is the method DeleteAllOnSubmit. I’ve never used this method, but he’s kind of 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 (only extension methods), 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);
    }
}

Use:

contexto.Receitas.DeleteAllObjects(contexto.Receitas.Where(r => r.ProjetoId == 100 && r.ItemId == 5));
contexto.SaveChanges();
  • I used "manual code" and it worked. Thanks. Now just one more question: I tried to use DeleteAllOnSubmit and returns the error "does not a Definition ...". Because this occurs?

  • I think that’s the subject of another question.

  • Ok. I will create a post. Thanks again.

0

Follow 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();
 }
  • Thanks for the help. But you returned the following error: The sequence contains more than one element in the filter execution. And does not provide the .Removableoption. In the example this && c.ID_ITEM = 5 and should be && c.ID_ITEM == 5.

Browser other questions tagged

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