EF Core - CRUD Operations

Entity Framework Core (EF Core) provides a powerful framework for performing CRUD (Create, Read, Update, Delete) operations on your database using .NET objects. This tutorial covers the basic CRUD operations with examples to help you manage data efficiently in your applications.


1. Creating Data

Creating data involves adding new records to your database. Use the Add or AddRange methods on a DbSet to add new entities.

        
            
using (var context = new ApplicationDbContext())
{
    var newProduct = new Product { Name = "New Product", Price = 99.99m };
    context.Products.Add(newProduct);
    context.SaveChanges();
}
        
    

In this example, a new product is added to the Products table, and changes are saved to the database.


2. Reading Data

Reading data involves querying the database to retrieve records. Use LINQ queries to fetch data from a DbSet.

        
            
using (var context = new ApplicationDbContext())
{
    var expensiveProducts = context.Products
                                   .Where(p => p.Price > 50)
                                   .ToList();
}
        
    

This example demonstrates how to retrieve all products with a price greater than 50.


3. Updating Data

Updating data involves modifying existing records in the database. When you retrieve an entity from the database, EF Core automatically tracks it, so you can change its properties and call SaveChanges() to update the database. However, there are scenarios where you need to explicitly use the Update method.


3.1 Updating with SaveChanges

When you retrieve an entity in the same context instance and modify it, EF Core automatically tracks the changes. Simply call SaveChanges() to persist the changes.

        
            
using (var context = new ApplicationDbContext())
{
    // Retrieve and update an existing product
    var product = context.Products.First(p => p.Name == "Existing Product");
    product.Price = 79.99m;
    context.SaveChanges();
}
        
    

In this example, the product's price is updated and saved without explicitly calling Update.


3.2 Updating with Update Method

Use the Update method when dealing with detached entities or when the entity was not retrieved in the same context instance.

        
            
using (var context = new ApplicationDbContext())
{
    // Simulating a detached entity scenario
    var detachedProduct = new Product { Id = 1, Name = "Detached Product", Price = 89.99m };

    // Update the detached entity
    context.Products.Update(detachedProduct);
    context.SaveChanges();
}
        
    

This example demonstrates how to update a detached entity using the Update method.


4. Deleting Data

Deleting data involves removing records from the database. Use the Remove or RemoveRange methods to delete entities.

        
            
using (var context = new ApplicationDbContext())
{
    var product = context.Products.First(p => p.Name == "Old Product");
    context.Products.Remove(product);
    context.SaveChanges();
}
        
    

This example demonstrates how to delete a product from the database.



5. Asynchronous CRUD Operations

EF Core supports asynchronous operations, which are essential for improving application responsiveness. Use asynchronous versions of CRUD methods for non-blocking database access.

        
            
using (var context = new ApplicationDbContext())
{
    // Asynchronous read
    var products = await context.Products
                                .Where(p => p.Price > 50)
                                .ToListAsync();

    // Asynchronous create
    var newProduct = new Product { Name = "Async Product", Price = 109.99m };
    await context.Products.AddAsync(newProduct);
    await context.SaveChangesAsync();

    // Asynchronous update
    var product = await context.Products.FirstAsync(p => p.Name == "Async Product");
    product.Price = 89.99m;
    await context.SaveChangesAsync();

    // Asynchronous delete
    context.Products.Remove(product);
    await context.SaveChangesAsync();
}
        
    

This example shows how to perform asynchronous read and write operations using EF Core.


6. Best Practices for CRUD Operations

Here are some best practices for performing CRUD operations in EF Core:


Summary

EF Core simplifies CRUD operations, providing a seamless way to interact with your database using .NET objects. By following best practices and leveraging EF Core's features, you can build efficient and reliable data-driven applications.