CRUD Operations in Entity Framework Core

What are CRUD Operations?

CRUD stands for Create, Read, Update, and Delete, which are the basic operations for interacting with a database. Entity Framework Core simplifies these operations by allowing developers to use .NET objects to manipulate database records.

  • Create: Add new records to the database.
  • Read: Retrieve data from the database.
  • Update: Modify existing records.
  • Delete: Remove records from the database.

Setting Up Entity Framework Core

Ensure you have a DbContext and models set up for your application. For this example, let’s assume we have a Customer model and a configured ApplicationDbContext.


// Models/Customer.cs
public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string City { get; set; }
}

// DbContext/ApplicationDbContext.cs
public class ApplicationDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
}

                

CRUD Operations Examples

Here are the basic CRUD operations demonstrated step-by-step:

1. Create (Add New Record)


// Adding a new customer
using (var context = new ApplicationDbContext())
{
    var customer = new Customer
    {
        Name = "John Doe",
        Email = "john.doe@example.com",
        City = "New York"
    };

    context.Customers.Add(customer);
    context.SaveChanges();
}

                

This code creates a new customer record in the database.

2. Read (Retrieve Records)


// Fetching all customers
using (var context = new ApplicationDbContext())
{
    var customers = context.Customers.ToList();
}

                

This query retrieves all records from the Customers table.

3. Update (Modify a Record)


// Updating a customer's information
using (var context = new ApplicationDbContext())
{
    var customer = context.Customers.FirstOrDefault(c => c.Id == 1);
    if (customer != null)
    {
        customer.City = "Los Angeles";
        context.SaveChanges();
    }
}

                

The FirstOrDefault method fetches the specific record, which is then updated and saved back to the database.

4. Delete (Remove a Record)


// Deleting a customer
using (var context = new ApplicationDbContext())
{
    var customer = context.Customers.FirstOrDefault(c => c.Id == 1);
    if (customer != null)
    {
        context.Customers.Remove(customer);
        context.SaveChanges();
    }
}

                

This code removes the customer with Id = 1 from the database.