DbContext, Entities & Fluent API

DbContext, Entities & Fluent API in .NET: Entity Framework Core (EF Core) is Microsoft's official Object-Relational Mapper (ORM).

Entity Framework Core (EF Core) is Microsoft's official Object-Relational Mapper (ORM). It allows developers to interact with relational databases using strongly-typed C# objects instead of raw SQL queries.


1. Designing Clean Entities with Navigation Properties

public class Course
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public string Title { get; set; } = string.Empty;
    public string Slug { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public bool IsPublished { get; set; }
    public DateTime CreatedAtUtc { get; set; } = DateTime.UtcNow;

    // Navigation property: One Course has many Lessons
    public List<Lesson> Lessons { get; set; } = new();
}

public class Lesson
{
    public Guid Id { get; set; } = Guid.NewGuid();
    public Guid CourseId { get; set; }
    public string Title { get; set; } = string.Empty;
    public int OrderIndex { get; set; }

    // Inverse Navigation
    public Course? Course { get; set; }
}

2. Fluent API Configuration vs Attributes

While Data Annotations ([Required], [MaxLength]) can be placed directly on properties, enterprise architectures prefer Fluent API configurations inside separate mapping classes to keep domain models clean:

public class CourseConfiguration : IEntityTypeConfiguration<Course>
{
    public void Configure(EntityTypeBuilder<Course> builder)
    {
        builder.ToTable("courses");

        builder.HasKey(c => c.Id);

        builder.Property(c => c.Title)
               .IsRequired()
               .HasMaxLength(200);

        builder.Property(c => c.Slug)
               .IsRequired()
               .HasMaxLength(250);

        builder.HasIndex(c => c.Slug)
               .IsUnique(); // Database unique constraint

        builder.Property(c => c.Price)
               .HasPrecision(18, 2);

        // One-to-Many Relationship Configuration
        builder.HasMany(c => c.Lessons)
               .WithOne(l => l.Course)
               .HasForeignKey(l => l.CourseId)
               .OnDelete(DeleteBehavior.Cascade);
    }
}

3. Registering DbContext in Program.cs

builder.Services.AddDbContext<AppDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"), sqlOptions =>
    {
        // Automatically retry transient connection failures
        sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null);
    });
});