Entity Framework CRUD Operations: Setup and Examples

In this guide, we will demonstrate how to perform database operations using Entity Framework (EF). EF is a powerful Object-Relational Mapping (ORM) tool that simplifies database interaction in .NET applications. CRUD operations (Create, Read, Update, Delete) are fundamental operations in database management.

1. Installing Entity Framework

To get started with Entity Framework, we need to add the necessary NuGet packages to the project. Follow these steps:

  1. Create a Project:

    • Open Visual Studio and create a new Console Application project.
  2. Install NuGet Package:

    • Right-click on the project and select NuGet Package Manager -> Manage NuGet Packages.
    • Search for Microsoft.EntityFrameworkCore and install it.
    • Alternatively, you can install it via the Package Manager Console using the following command:
Install-Package Microsoft.EntityFrameworkCore

Database Connection:

  • To connect to the database, you'll need to configure a DbContext class.

2. Defining DbContext and Model Class

First, we need to define a model class and a DbContext class.

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS;Database=EFTestDb;Trusted_Connection=True;");
    }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
  • The ApplicationDbContext class manages the database connection.
  • The Product class represents a table in the database for storing product data.

3. CRUD Operation Examples

Create - Adding Data

To add a new product to the database, we use the Add method. Here's an example:

public static void CreateProduct()
{
    using (var context = new ApplicationDbContext())
    {
        var product = new Product
        {
            Name = "Laptop",
            Price = 1500.00M
        };

        context.Products.Add(product);
        context.SaveChanges();
    }
}
  • The Add method adds a new entity to the DbSet.
  • The SaveChanges method commits the changes to the database.

Read - Reading Data

To read data from the database, we can use methods like Find or FirstOrDefault.

public static void ReadProduct(int productId)
{
    using (var context = new ApplicationDbContext())
    {
        var product = context.Products.FirstOrDefault(p => p.Id == productId);
        
        if (product != null)
        {
            Console.WriteLine($"Product ID: {product.Id}, Name: {product.Name}, Price: {product.Price}");
        }
        else
        {
            Console.WriteLine("Product not found.");
        }
    }
}

The FirstOrDefault method retrieves the first entity that matches the specified condition. If no entity is found, it returns null.

 

Update - Updating Data

To update an existing record, we retrieve it and change its properties.

public static void UpdateProduct(int productId, string newName, decimal newPrice)
{
    using (var context = new ApplicationDbContext())
    {
        var product = context.Products.FirstOrDefault(p => p.Id == productId);

        if (product != null)
        {
            product.Name = newName;
            product.Price = newPrice;
            context.SaveChanges();
        }
    }
}
  • The SaveChanges method commits the changes to the database.
  • Here, we updated the name and price of the product.

 

Delete - Deleting Data

To delete a product, we use the Remove method.

public static void DeleteProduct(int productId)
{
    using (var context = new ApplicationDbContext())
    {
        var product = context.Products.FirstOrDefault(p => p.Id == productId);

        if (product != null)
        {
            context.Products.Remove(product);
            context.SaveChanges();
        }
    }
}
  • The Remove method deletes the specified entity from the DbSet.
  • The SaveChanges method saves the changes to the database.

 

4. Summary and Tips

  • Entity Framework makes it easier and safer to interact with databases by providing a higher-level API for performing CRUD operations.
  • The DbContext class is used to manage database operations, and it provides a simple and clear API for CRUD operations.
  • In each CRUD operation, we call SaveChanges to persist the changes to the database.

These examples demonstrate how to perform basic database operations with EF. You can explore more advanced features like handling related tables, managing transactions, and using LINQ queries for complex operations.

If you have any questions or need further assistance, feel free to ask!