Free Web Development Online Tutorials, Learn to Code
Learn Entity Framework with C#, Entity Framework Core, Code First, DB First Approach

Entity Framework Core Update Example in C#

Here we learn how to update data using entity framework core. Updating single entity and also bulk update, means updating multiple rows together.

How Update works in EF Core

In entity framework core EntityState is changed automatically, EF Core API can keep track of all the entities retrieved using the context, so when you make any changes in any context object, EntityState become Modified, and finally when we call the SaveChanges() method, all new changes made to context gets saved to database.

Updating single row in EF Core

To update data in one particular row, we should first fetch the row from database, and then make necessary changes in properties, set new values wherever we need, finally call save changes method.

public Student UpdateStudent(Student student)
{
Student _s = null;
using (EFContext context = new EFContext())
{
_s = context.tbStudent
.Where(s => s.StuId == student.StuId)
            .FirstOrDefault<Student>();
    if (_s != null)
    {
        _s.Firstname = student.Firstname;
        _s.Lastname = student.Lastname;
        _s.Email = student.Email;
        _s.ContactNumber = student.ContactNumber;
        context.SaveChanges();
    }
}
return _s;
}

Bulk Update using EF Core

To update multiple rows in Entity Framework earlier we used to loop through the collection and set updated value for each row then finally call save changes.

Now there is a UpdateRange() method , which accept multiple entities, and update them together in database, Here is how you can update collection object in entity framework core.

using (WTRDBContext context = new WTRDBContext())
{
    List<tbstudent> students = new List<tbstudent>()
        {
        new tbStudent(){StuId=1, ContactNumber="98952"},
        new tbStudent(){StuId=3, ContactNumber="48752"},
        new tbStudent(){StuId=5, ContactNumber="47521"}
        };
                                
    context.Students.UpdateRange(students);
    context.SaveChanges();
}

Remember while executing update statement each entity key has to match with key in database table, otherwise it will throw exception

There are some additional extension utilities, like one by NuGet EFCore.BulkExtensions

Comment
Name
Email
Website
Subscribe
 
Update example in EF Core