C# / .NET Compendium PLEN
.NET / C# / Entity Framework Core

Entity Framework Core - the basics

DbContext and DbSet - the foundation

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    public DbSet<Order> Orders { get; set; }
    public DbSet<Customer> Customers { get; set; }
    public DbSet<OrderItem> OrderItems { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>()
            .HasMany(o => o.Items)
            .WithOne(i => i.Order)
            .HasForeignKey(i => i.OrderId);
    }
}

DbSet<T> represents a table in the database and implements IQueryable<T> (as we discussed earlier) - every query on a DbSet is built as an expression tree until you request materialisation.

Change Tracking - the default behaviour

var order = await _context.Orders.FirstAsync(o => o.Id == 1);
order.Status = "Shipped"; // EF Core AUTOMATICALLY tracks this change

await _context.SaveChangesAsync(); // generates an UPDATE only for the changed fields

EF Core automatically detects changes on objects that were fetched through the same DbContext - you don't have to say manually "this object has changed".

AsNoTracking() - turning tracking off for reads

// With tracking (the default) - EF Core keeps a "snapshot" to compare on SaveChanges
var orders = await _context.Orders.ToListAsync();

// Without tracking - faster, less memory, when you ONLY read the data (you won't modify it)
var readOnlyOrders = await _context.Orders.AsNoTracking().ToListAsync();

When to use AsNoTracking(): for all read-only queries (e.g. displaying a list in the API, reports) - it eliminates the change tracker's overhead, which with large data sets makes a real performance difference.

The N+1 problem - a classic performance trap

// ❌ The N+1 problem - one query for the orders + N queries for the customer of each of them
var orders = await _context.Orders.ToListAsync();
foreach (var order in orders)
{
    Console.WriteLine(order.Customer.Name); // LAZY LOADING - a separate SQL query for EVERY order!
}
// ✅ Eager loading z Include - JEDNO zapytanie z JOIN
var orders = await _context.Orders
    .Include(o => o.Customer)
    .ToListAsync();

foreach (var order in orders)
{
    Console.WriteLine(order.Customer.Name); // the data is already loaded, no additional queries
}

Include() generates a JOIN in SQL and loads the related data in the same query - this is the standard solution to the N+1 problem in EF Core.

// Include wielopoziomowy (ThenInclude)
var orders = await _context.Orders
    .Include(o => o.Customer)
    .Include(o => o.Items).ThenInclude(i => i.Product)
    .ToListAsync();

Migrations - managing the database schema

dotnet ef migrations add AddOrderStatusColumn   # generuje plik migracji na podstawie zmian w modelu
dotnet ef database update                        # stosuje migracje do bazy danych
dotnet ef migrations remove                       # removes the last, not yet applied migration
dotnet ef database update PreviousMigrationName    # rollback do konkretnej migracji

A migration is a C# file generated automatically, describing the difference between the previous and the current model (Up()/Down()):

public partial class AddOrderStatusColumn : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.AddColumn<string>(name: "Status", table: "Orders", type: "nvarchar(50)", nullable: true);
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.DropColumn(name: "Status", table: "Orders");
    }
}

Async guidelines - always asynchronous

// ✅ Correct - EF Core I/O operations should always be async
var order = await _context.Orders.FirstOrDefaultAsync(o => o.Id == id);
await _context.SaveChangesAsync();

// ❌ Wrong - blocks a thread for the duration of the I/O, wastes resources (especially in Web API under load)
var order = _context.Orders.FirstOrDefault(o => o.Id == id);
_context.SaveChanges();

Summary of the key methods

Method Purpose
AsNoTracking() Turns off change tracking, faster read-only queries
Include()/ThenInclude() Eager loading, avoids the N+1 problem
FirstOrDefaultAsync() Fetching a single record or null
AnyAsync() Checking existence without fetching data
CountAsync() Counting without materialising all the records
SaveChangesAsync() Saving all the tracked changes as a transaction
Buy me a coffee