Update Multiple Rows in Entity Framework from a list of ids

asp.net-mvc c# entity-framework sql

Question

I am trying to create a query for entity framework that will allow me to take a list of ids and update a field associated with them.

Example in SQL:

UPDATE Friends
SET msgSentBy = '1234'
WHERE id IN (1, 2, 3, 4)

How do I convert the above into entity framework?

1
82
2/6/2014 2:02:04 AM

Accepted Answer

something like below

var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
    var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
    friends.ForEach(a=>a.msgSentBy='1234');
    db.SaveChanges();
}

UPDATE:

you can update multiple fields as below

friends.ForEach(a =>
                      {
                         a.property1 = value1;
                         a.property2 = value2;
                      });
145
2/6/2014 2:27:22 AM

Popular Answer

There are two open source projects allowing this: EntityFramework.Extended and Entity Framework Extensions.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow