Update multiple records with Entityframework

Asked

Viewed 1,246 times

2

Assuming I have the following appointment:

UPDATE tb_foo SET idoso = 1 WHERE idade > 65

To carry out this same process in Lilli, I have

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

This is the most performative way to perform a multi-record update in the database?

The query is executed when it arrives in foreach, but the updates are performed in the SaveChanges, thus generating a process more than the execution of the Update with a clause where in the database itself (or using ADO.NET). This thinking is correct?

  • 1

    In the .SaveChanges() it will perform several updates. EF does not support batch update no. I will try to find a text I have read about it and put here if I can.

1 answer

2


There are some ways to update, I got the code below of that 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 put more for you to see that there are several ways to do it. The fact is that none of them will update with where id > 30

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

I particularly when I need to do a simple update on several records I use a same database procedure. It all depends on your infrastructure, BD capacity and application server.

UPDATING

Regarding an official position of Microsoft on this I do not know if it exists. Until mid-last year (if memory serves me correctly) I looked for something and found nothing.

You can try some third party design to do this:

Entity Framework Extended Library

Entity Framework Extensions (Multiple Entity updates)

When there is a solution for this native EF probably these projects will even announce.

  • Yes yes, @Ricardo. The biggest doubt was about the behavior of Inglo. Do you have any source on " fact is that none of them will update with Where id > 30"? I searched MSDN and some reference books but I could not find this behavior

  • I updated the answer with what little I know

Browser other questions tagged

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