Entity Framework Core: CRUD Operations

A comprehensive guide to performing Create, Read, Update, and Delete operations using Entity Framework Core.

CRUD Operations with Entity Framework Core

Entity Framework Core (EF Core) simplifies database interactions by providing an object-relational mapper (ORM). This allows you to work with your database using .NET objects, abstracting away much of the underlying SQL code. This section focuses on the fundamental Create, Read, Update, and Delete (CRUD) operations.

1. Creating New Data (Create)

To create new records, you instantiate your entity objects and add them to a DbSet in your DbContext. The changes are then persisted to the database by calling SaveChanges().

Example: Adding a New Product

using System.Linq;
using Microsoft.EntityFrameworkCore;

// Assuming Product is your entity and context is an instance of your DbContext
var newProduct = new Product
{
    Name = "Wireless Mouse",
    Price = 25.99,
    StockQuantity = 150
};

context.Products.Add(newProduct);
await context.SaveChangesAsync();

2. Reading Data (Read)

Reading data involves querying your DbContext. EF Core supports LINQ (Language Integrated Query), making queries expressive and type-safe. You can retrieve single entities, collections, or perform projections.

Example: Retrieving Products

// Get all products
var allProducts = await context.Products.ToListAsync();

// Get a product by ID
var productById = await context.Products.FirstOrDefaultAsync(p => p.Id == 1);

// Querying with filtering and ordering
var expensiveProducts = await context.Products
    .Where(p => p.Price > 50)
    .OrderByDescending(p => p.Price)
    .ToListAsync();

3. Updating Existing Data (Update)

To update an existing entity, first retrieve it from the database. Then, modify its properties. EF Core tracks changes to entities, so calling SaveChanges() after modifications will automatically generate the appropriate UPDATE SQL statements.

Example: Updating a Product's Price

// Retrieve the product to update
var productToUpdate = await context.Products.FindAsync(1);

if (productToUpdate != null)
{
    // Modify its properties
    productToUpdate.Price = 29.95;
    productToUpdate.StockQuantity += 10;

    // Persist the changes
    await context.SaveChangesAsync();
}

Important: Detecting Changes

EF Core's change tracking automatically detects modifications made to retrieved entities. If you detach an entity and then reattach it, you might need to explicitly mark it as modified if its state hasn't been tracked correctly.

4. Deleting Data (Delete)

To delete an entity, you first retrieve it and then use the Remove() method on the corresponding DbSet. Finally, call SaveChanges() to execute the DELETE command.

Example: Deleting a Product

// Retrieve the product to delete
var productToDelete = await context.Products.FindAsync(2);

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

    // Persist the deletion
    await context.SaveChangesAsync();
}

Batch Operations

For performance-critical scenarios, especially when dealing with a large number of records, consider using batch update or delete operations. Libraries like EntityFrameworkCore.BatchUpdate can help optimize these operations by translating them into a single SQL statement rather than multiple individual ones.

By mastering these fundamental CRUD operations, you can effectively manage your application's data using Entity Framework Core.