-2

Good day guys,

I'm trying to save a multiple records.

I've done my research but none of them actually works on my end.

Here's my code:

var dataToUpdate = context.Employees.ToList(); 

using(var db = context){
   var department= "IT";

   dataToUpdate.ForEach(x=>{
       x.department = department;
   });

   db.SaveChanges()
}

Source here: EF - Update multiple rows in database without using foreach loop but it doesn't work.

I tried to put breakpoints and try catch and my breakpoint goes to db.SaveChanges without error. But when I check the data from db, no changes have occurred.

Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
AppleCiderYummy
  • 369
  • 1
  • 7
  • 20

1 Answers1

2

Look at! you are pulling and updating data from two different contexts. Actually it should be from same context as follows:

using(var db = context)
{
  var dataToUpdate = db.Employees.ToList();

   var department= "IT";

   dataToUpdate.ForEach(x=>{
       x.department = department;
   });

   db.SaveChanges();
}

Now it should work.

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114