Part 5: Entity Framework Core: DbContext, DbSets, and Database Setup

Part 5 Technology Updated September 12, 2026

Entity Framework Core: DbContext, DbSets, and Database Setup

Entity Framework (EF) Core is Microsoft's official Object-Relational Mapper (ORM). It abstracts SQL queries into strongly-typed C# LINQ expressions.


1. Installing NuGet Packages

dotnet add EnterpriseFullstack.Infrastructure package Microsoft.EntityFrameworkCore.SqlServer
dotnet add EnterpriseFullstack.Infrastructure package Microsoft.EntityFrameworkCore.Tools
dotnet add EnterpriseFullstack.API package Microsoft.EntityFrameworkCore.Design

2. Defining Domain Entities

// EnterpriseFullstack.Core/Entities/Product.cs
namespace EnterpriseFullstack.Core.Entities;

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public string PictureUrl { get; set; } = string.Empty;
    public int ProductTypeId { get; set; }
    public ProductType ProductType { get; set; } = null!;
    public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}

3. Implementing the DbContext

// EnterpriseFullstack.Infrastructure/Data/StoreContext.cs
using Microsoft.EntityFrameworkCore;
using EnterpriseFullstack.Core.Entities;

namespace EnterpriseFullstack.Infrastructure.Data;

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

    public DbSet<Product> Products => Set<Product>();
    public DbSet<ProductType> ProductTypes => Set<ProductType>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        // Apply configurations from assembly
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(StoreContext).Assembly);
    }
}