ef core update multiple items and then save

asp.net-core c# entity-framework entity-framework-core

Question

I need to update multiple items in the database.

My questions:

  • do I need to use ctx.Items.Update(item); ?
  • can I first update all the items in loop and then use ctx.SaveChangesAsync()?

Basically I need to speed this up so I assume if I update the items properties and then call SaveChangesAsync() for all of them it will make one call to the database rather that doing it inside the loop for each item?

What about the ctx.Items.Update(item)? does it make any sense having it? I think I need this otherwise how will it know what to update, right?

using (var ctx = new MyCOntext())
{
     var allToBeUpdated = await ctx.Items.Where(t=>t.ToBeUpdated == true).ToListAsync();

      foreach (var item in allToBeUpdated)
      {
            item.ToBeUpdated = false;

            ctx.Items.Update(item); // do I need this ?
      }

       await ctx.SaveChangesAsync();  // can I have the save changes async out of foreach? So I can update all the items at once rather than one by one
}
1
0
9/7/2017 8:32:12 AM

Accepted Answer

The below should be sufficient to save the values

using (var ctx = new MyCOntext())
{
     var allToBeUpdated = await ctx.Items.Where(t=>t.ToBeUpdated == true).ToListAsync();

      foreach (var item in allToBeUpdated)
      {
            item.ToBeUpdated = false; //change tracking will take care of tracking what is changed
      }

       await ctx.SaveChangesAsync();  // Save changes outside will update all the pending changes 
}
3
9/7/2017 8:32:43 AM


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