13. Databases with Entity Framework Core

Entity Framework Core (EF Core) is an object-relational mapper. It lets you work with database tables as C# classes and write queries with LINQ instead of raw SQL. A DbContext represents the database and each DbSet<T> represents a table. Install a provider package such as Microsoft.EntityFrameworkCore.SqlServer, set the connection string in appsettings.json, and use migrations to create and update the database.

Key points

  • dotnet ef migrations add InitialCreate creates a migration.
  • dotnet ef database update applies migrations to the database.
  • Use async methods such as ToListAsync and SaveChangesAsync.
  • Use parameters or LINQ, never join user text into SQL strings.

Example: DbContext and registration

Data/AppDbContext.cs
public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options) { }

    public DbSet<Student> Students { get; set; }
}

// Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")));
Show explanation

The Students property maps to a Students table. The connection string is read from appsettings.json.

Example: Using the context in a controller

Controllers/StudentsController.cs
private readonly AppDbContext _db;
public StudentsController(AppDbContext db) => _db = db;

public async Task<IActionResult> Index()
{
    var students = await _db.Students
        .Where(s => s.Age >= 18)
        .OrderBy(s => s.Name)
        .ToListAsync();
    return View(students);
}
Show explanation

EF Core turns this LINQ into a SQL SELECT with a WHERE and ORDER BY and returns Student objects.