1

I have the following code:

List<Item> csItems = (from i in context.Items
                      where i.CSItem == true
                      select i).ToList<Item>();
csItems.ForEach(i => i.Active = false);
context.SaveChanges();

Seems like this is horribly inefficient as I have to read the entire table in first, then update the tables. Is there a better way to do this so that I am only doing an update without reading everything?

Scottie
  • 11,050
  • 19
  • 68
  • 109

2 Answers2

2

Linq2EF doesn't have a built-in bulk update, but you can use Alex James, articles to do it yourself, actually you should implement it yourself. Also simple way is using stored procedures. But if you want to have it yourself you can read all of 4 article series, they are easy to read.

Community
  • 1
  • 1
Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83
1

There is no need to build the List<T> of the items. I, personally, would just enumerate the results and set the values:

IQueryable<Item> csItems = (from i in context.Items
                  where i.CSItem == true
                  select i);
foreach(var item in csItems)
     item.Active = false;

context.SaveChanges();

Note that there is no bulk-update functionality built-in with Entity Framework, so doing something more efficient would require some other technique.

Community
  • 1
  • 1
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373