Updating the Record

Let us try to update the salary of an inserted employee record using Entity Framework:


Go to https://goo.gl/4k5J6a to access the code.
static void UpdateSalary()
{
using (var db = new EmployeeDbContext())
{
Employee employee = db.Employees.Where(emp
=> emp.EmployeeId == 1).FirstOrDefault();
if (employee != null)
{
employee.Salary = 6500;
int recordsUpdated = db.SaveChanges();
Console.WriteLine("Records updated:" +recordsUpdated);
Console.ReadLine();
}
}
}

In the preceding method, we find the employee with EmployeeId = 1. Then, we update the salary of the employee to 6500 and save the employee object to the database. Please note that, in the preceding method, we interact with the database a couple of times—once to find the correct employee record (read operation) and again to update the record (update operation):

static void Main(string[] args)
{
UpdateSalary();
}

Also make sure you add using System.Linq; to the top of the file.

The Main method is updated to call the UpdateSalary method. When you query the database, you should see the record with the updated information:

Make sure you click on the Refresh button.