entity-framework-eliminar-registros

Deleting Data in Entity Framework

  • 4 min

In Entity Framework, record deletion is one of the fundamental CRUD operations, and the last one we have left to cover.

Deleting records involves removing existing entities from the database (obvious,😊). For this, Entity Framework provides the Remove and RemoveRange methods.

As with the rest of the operations, when we delete a record from the DbContext, these are not executed immediately in the database.

Instead, EF marks them for deletion. The changes will take effect in the database when we call the SaveChanges method.

Deleting Records with Remove

The Remove method is used to delete a single record from the database. This method marks the entity as “deleted” in the context.

DbContext.Remove(entity);
Copied!

Suppose we have a Product entity and we want to delete a specific product from the database:

using (var context = new MyContext())
{
    // Find the product to delete
    var product = context.Products.Find(1); // Let's assume the ID is 1

    if (product != null)
    {
        // Mark the product for deletion
        context.Products.Remove(product);

        // Apply the changes to the database
        context.SaveChanges();
    }
}
Copied!

In this example:

  1. We find the product with ID 1 using the Find method.
  2. If the product exists, we mark it for deletion with Remove.
  3. Finally, we call SaveChanges to apply the deletion in the database.

Multiple Deletion with RemoveRange

The RemoveRange method is an extension of Remove that allows deleting multiple records at once.

This is useful when we need to delete a collection of entities, as it reduces the number of database operations.

DbContext.RemoveRange(entities);
Copied!

Suppose we want to delete all products with a price less than 10:

using (var context = new MyContext())
{
    // Find the products to delete
    var cheapProducts = context.Products
                                .Where(p => p.Price < 10)
                                .ToList();

    if (cheapProducts.Any())
    {
        // Mark the products for deletion
        context.Products.RemoveRange(cheapProducts);

        // Apply the changes to the database
        context.SaveChanges();
    }
}
Copied!

In this example:

  1. We use LINQ to filter products with a price less than 10.
  2. If there are products that meet the condition, we mark them for deletion with RemoveRange.
  3. We call SaveChanges to apply the deletion in the database.

Like AddRange, DeleteRange can reduce the number of queries to the database.

But it is not a bulk operation. That is, the performance can still be improved 😅

Common Cases