Update multiple records with EntityFramework

2

Assuming I have the following query:

UPDATE tb_foo SET idoso = 1 WHERE idade > 65

To perform this same process in linq, I have

IEnumerable<Foo> foos = contexto.Foos.Where(e => e.Idade > 65);
foreach(var item in foos)
{
      item.Idoso = true;
}
contexto.SaveChanges();

Is this the most performative way to perform an update of multiple records in the database using linq?

Query is executed when it arrives at foreach , but updates is done at SaveChanges thus generating a process more than the execution of Update with a where clause in the database itself (or using ADO.NET). Is this thought correct?

    
asked by anonymous 05.01.2016 / 20:33

1 answer

2

There are a few ways to get the update, I've gotten the code below from this answer :

var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>a.status=true);
    db.SubmitChanges();
}

using (var db=new SomeDatabaseContext())
{
     db.SomeTable
       .Where(x=>ls.Contains(x.friendid))
       .ToList()
       .ForEach(a=>a.status=true);

     db.SubmitChanges();
}

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
    }
    db.SubmitChanges();
}

I've put more to you that there are several ways to do it. The fact is that none of them will update with where id > 30

The .ForEach() is nothing more than a for each made in the result. The only advantage is that it gets cleaner using it.

I particularly when I need to do a simple update on multiple records I use a same database procedure. It all depends on your infra, capacity of the DB and the application server.

UPDATING

Regarding an official Microsoft position on this I do not know if it exists. Until the middle of last year (if memory does not fail me) I looked for something and did not find anything.

You can try some projects made by third parties to do this:

Entity Framework Extended Library

Entity Framework Extensions (Multiple entity updates)

When there is a solution for that native to EF, these projects will probably advertise.

    
05.01.2016 / 20:41