Entity Framework Core

Entity Framework Core (EF Core) is a modern, cross-platform, open-source version of the popular Microsoft Entity Framework data access technology.

EF Core is designed to be lightweight, extensible, and high-performance. It allows .NET developers to work with databases using .NET objects, abstracting away much of the complexity of direct SQL interactions.

Key Concepts

1. DbContext

The DbContext class is the primary gateway to interact with your data. It represents a session with the database and can be used to query and save data. You typically create a class that derives from DbContext and includes DbSet<TEntity> properties for each entity in your model.


using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("YourConnectionString");
    }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public ICollection<Product> Products { get; set; }
}

            

2. Migrations

Migrations are used to incrementally update your database schema to match your EF Core model. They allow you to manage database schema changes over time in a version-controlled manner.

Common commands:

3. Querying Data

You can query data using LINQ (Language Integrated Query) against your DbSet properties.


using (var context = new MyDbContext())
{
    // Get all products
    var allProducts = context.Products.ToList();

    // Get products with price greater than 50
    var expensiveProducts = context.Products
                                .Where(p => p.Price > 50)
                                .OrderBy(p => p.Name)
                                .ToList();

    // Include related data (Category)
    var productsWithCategories = context.Products
                                        .Include(p => p.Category)
                                        .ToList();
}

            

4. Saving Data

Adding, updating, and deleting entities is handled through the DbContext.


using (var context = new MyDbContext())
{
    // Add a new product
    var newProduct = new Product { Name = "Wireless Mouse", Price = 25.99m, CategoryId = 1 };
    context.Products.Add(newProduct);
    context.SaveChanges(); // Persists changes to the database

    // Update an existing product
    var productToUpdate = context.Products.Find(1); // Assuming a product with ID 1 exists
    if (productToUpdate != null)
    {
        productToUpdate.Price = 27.50m;
        context.SaveChanges();
    }

    // Delete a product
    var productToDelete = context.Products.Find(2); // Assuming a product with ID 2 exists
    if (productToDelete != null)
    {
        context.Products.Remove(productToDelete);
        context.SaveChanges();
    }
}

            

Note on Change Tracking

EF Core automatically tracks changes to entities retrieved from the database. When SaveChanges() is called, EF Core generates the necessary SQL commands to synchronize the database with the changes made to the tracked entities.

5. Providers

EF Core supports various database providers, allowing you to work with different database systems like SQL Server, PostgreSQL, MySQL, SQLite, and more. You need to install the appropriate NuGet package for your chosen provider and configure it in OnConfiguring or via dependency injection.

Example for PostgreSQL:


optionsBuilder.UseNpgsql("YourPostgresConnectionString");

            

Tip: Dependency Injection

In modern .NET applications (like ASP.NET Core), it's highly recommended to use dependency injection for managing DbContext instances. This simplifies configuration and lifetime management.

Further Reading