Update Operation in EF Core
The Update operation in Entity Framework Core allows you to modify existing records in the database.
Key Topics
Updating Records
Example
using System;
using System.Linq;
class Program
{
static void Main()
{
using (var context = new MyDbContext())
{
var employee = context.Employees.FirstOrDefault(e => e.Name == "John Doe");
if (employee != null)
{
employee.Department = "Finance";
context.SaveChanges();
Console.WriteLine("Record updated successfully.");
}
}
}
}
Explanation: This example retrieves a specific employee record, updates the department, and calls SaveChanges()
to persist the changes.
Key Takeaways
- Retrieve the entity to be updated, make the changes, and call
SaveChanges()
. - EF Core automatically tracks changes to entities.