EF Core Architecture

Intermediate Updated May 20, 2025

🧱 EF Core Architecture: A Visual Breakdown

Here's a simplified text-based diagram to visualize EF Core’s role in a .NET application:

+-------------------+      LINQ Queries / C# Code      +---------------------+
|                   | --------------------------------> |                     |
|   Application     |                                   |    DbContext        |
|                   | <-------------------------------- |                     |
+-------------------+        C# Objects (Entities)      +---------------------+
                                                        |
                                                        |     Change Tracking
                                                        v
                                               +-------------------+
                                               |     EF Core       |
                                               +-------------------+
                                                        |
                                                        v
                                               +-------------------+
                                               | Relational DB     |
                                               | (SQL Server, etc.)|
                                               +-------------------+

🧑‍💻 Defining Your Data Model

✅ Creating Entity Classes

Entities are plain C# classes that represent your database tables.

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

✅ Creating the DbContext

The DbContext represents a session with the database and provides APIs to perform operations.

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=.;Database=ShopDb;Trusted_Connection=True;");
    }
}

🚧 Code-First Migrations

EF Core allows you to generate database schema from your C# code.

🌀 Add Initial Migration

dotnet ef migrations add InitialCreate

💾 Apply the Migration

dotnet ef database update

This creates the database and tables based on your models.