Update Records in Entity Framework Core

Update Records in Entity Framework Core

The Entity Framework Core executes UPDATE statement in the database for the entities whose EntityState is Modified. The DbContext tracks of all entities and those that are modified it sets there EntityState 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.Department.Update(dept);
    context.SaveChanges();
}

The above code updates the Department name, of department with Id ‘1’, as 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.

Case when the .Update() will Insert a new record

If there is no valid property key value then EF core will set the EntityState to Added. The below code does not have 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.Department.Update(dept);
    context.SaveChanges();
}

Here the .Update() method will insert a new Research record on the Department table.

update method inserts a new record

Update Multiple Records

Use DbContext.UpdateRange() method to update multiple entities 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.Department.UpdateRange(modifiedDept);
    context.SaveChanges();
}

update multiple records

DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "WordPress, SEO, jQuery, HTML" and more.