-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.

13
  • 1
    what is dataToUpdate ? Commented Feb 12, 2019 at 7:49
  • it is from my list Commented Feb 12, 2019 at 7:51
  • It is clear that dataToUpdate did not come from this db. So it is not tracked here. Your question is far from complete. Commented Feb 12, 2019 at 7:51
  • I've updated the code @Petaflop & Henk Commented Feb 12, 2019 at 7:52
  • 1
    It has to be about [entity-framework-6] or [entity-framework-core], it can't be about both. Commented Feb 12, 2019 at 8:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Typical missing semicolon after db.SaveChanges() :)
@Petaflop Oh! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.