Delete Operation in EF Core
The Delete operation in Entity Framework Core allows you to remove records from the database.
Key Topics
Deleting 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)
{
context.Employees.Remove(employee);
context.SaveChanges();
Console.WriteLine("Record deleted successfully.");
}
}
}
}
Explanation: This example retrieves a specific employee record and removes it using the Remove()
method followed by SaveChanges()
.
Key Takeaways
- Use the
Remove()
method on the DbSet to delete an entity. - Call
SaveChanges()
to persist the deletion to the database.