ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

ASP.NET Core Tutorial• 9 min read

Entity Framework Core (EF Core) & DbContext

Code-First database migrations, LINQ queries, and relational mapping

Entity Framework Core (EF Core) is a lightweight, extensible, open-source Object-Relational Mapper (ORM) for .NET that enables developers to query and manipulate relational databases using strongly typed C# LINQ syntax.

DbContext and Code-First Migrations

DbContext: Represents a session with the database, exposing DbSet<TEntity> tables.

Code-First Workflow: You write C# classes, and EF Core automatically generates schema migration scripts.

LINQ Queries: C# queries like .Where(c => c.Price > 50).ToListAsync() are translated into optimized SQL at runtime.

AsNoTracking(): Essential query optimization for read-only endpoints that disables change tracking overhead.

DbContext Definition and LINQ Querying
using Microsoft.EntityFrameworkCore;

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

    public DbSet<Course> Courses => Set<Course>();
    public DbSet<Category> Categories => Set<Category>();
}

// Model Class
public class Course
{
    public int Id { get; set; }
    public string Title { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public int CategoryId { get; set; }
    public Category? Category { get; set; }
}

// CLI Migration Commands:
// dotnet ef migrations add InitialCourseSchema
// dotnet ef database update
The dotnet ef CLI synchronizes your C# models with database tables automatically.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which EF Core method should be called on read-only queries to disable change-tracking overhead and improve throughput?