The Entity Framework Core executes UPDATE statement in the database for the entities whose EntityState is Modified. The Database Context keeps tracks of all entities that have their EntityState value as modified.
I will use the DbContext.Update() method for updating entities.
Consider the below code:
var dept = new Department()
{
Id = 1,
Name = "Designing"
};
using (var context = new CompanyContext())
{
context.Update(dept);
await context.SaveChangesAsync();
}
The above code updates the Department name of the department with Id 1. It set’s its name to Designing.
The reason why EF Core does the update here is because the entity has a valid property key value (which is ‘1’ in this case). So it sets its EntityState to Modified.
If there is no valid property key value then EF core will set the EntityState to Added. The below given code does not have the Id property for Department entity, so on doing the update the EF core Inserts a new Department record on the database.
var dept = new Department()
{
Name = "Research"
};
using (var context = new CompanyContext())
{
context.Update(dept);
await context.SaveChangesAsync();
}
Here the .Update() method will insert a new Research record on the Department table.
Use DbContext.UpdateRange() method to Update Multiple Records at the same time.
Consider the below code where I am updating 3 Department records at the same time.
var dept1 = new Department()
{
Id = 1,
Name = "New Designing"
};
var dept2 = new Department()
{
Id = 2,
Name = "New Research"
};
var dept3 = new Department()
{
Id = 3,
Name = "New HR"
};
List<Department> modifiedDept = new List<Department>() { dept1, dept2, dept3 };
using (var context = new CompanyContext())
{
context.UpdateRange(modifiedDept);
await context.SaveChangesAsync();
}
The below code updates the Department name to ‘Admin_1’. This Department is the related record for the Employee Entity.
var dept = new Department()
{
Id = 5,
Name = "Admin_1"
};
var emp = new Employee()
{
Id = 1,
Name = "Matt_1",
Designation = "Head_1",
Department = dept
};
using (var context = new CompanyContext())
{
context.Update(emp);
await context.SaveChangesAsync();
}
When this code executes the employee having id as 1 gets his info changed to:
The related data which is the department also gets changed. This Employee Department name gets changed to “Admin_1”.
Download the source codes: