UpdateRange method of Entity Framework Core does not work

房东的猫 提交于 2021-02-08 11:54:17

问题


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?


回答1:


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

After



来源:https://stackoverflow.com/questions/63325587/updaterange-method-of-entity-framework-core-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!