yogihosting
yogihosting

Reputation: 6292

UpdateRange method of Entity Framework Core does not work

The UpdateRange method of Entity Framework Core is used here to update multiple records but it is not working.

My code is:

var dept1 = new Department()
{
    Id = 8,
    Name = "New Designing"
};

var dept2 = new Department()
{
    Id = 9,
    Name = "New Research"
};

var dept3 = new Department()
{
    Id = 102,
    Name = "New HR"
};

List<Department> modifiedDept = new List<Department>() { dept1, dept2, dept3 };

using (var context = new CompanyContext())
{
    context.UpdateRange(modifiedDept);
    await context.SaveChangesAsync();
}

And the error I get is:

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.'

What should be done in this case?

Upvotes: 1

Views: 21307

Answers (1)

Asherguru
Asherguru

Reputation: 1741

You are supposed to get data from database and modify data. Not creating new class.

using (var context = new JobContext())
{
    var depts = context.Department.Where(x => x.Id > 1).AsQueryable();
    depts.Where(x => x.Id == 2).FirstOrDefault().Name = "New Designing";
    depts.Where(x => x.Id == 3).FirstOrDefault().Name = "New Research";
    depts.Where(x => x.Id == 4).FirstOrDefault().Name = "New HR";

    context.UpdateRange(depts);
    context.SaveChanges();
}

Before

enter image description here

After

enter image description here

Upvotes: 10

Related Questions