user2818430
user2818430

Reputation: 6029

ef core update multiple items and then save

I need to update multiple items in the database.

My questions:

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
}

Upvotes: 0

Views: 3707

Answers (1)

Ramesh
Ramesh

Reputation: 13266

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 
}

Upvotes: 3

Related Questions