Skip to main content

Lesson 2 of 8

Fluent API Entity Configuration

Fluent API gives you full control over every aspect of database mapping: table names, column types and precision, indexes, relationships, cascade behavior, and value conversions. It keeps your domain entity classes clean of database concerns.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

IEntityTypeConfiguration - Production Configuration

IEntityTypeConfiguration - Production Configuration
using Microsoft.EntityFrameworkCore.Metadata.Builders;

// ━━ Separate configuration class per entity (Single Responsibility) ━━
public class ProductConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Products", "catalog"); // explicit schema

        // ━━ Primary key ━━
        builder.HasKey(p => p.Id);
        builder.Property(p => p.Id).HasDefaultValueSql("NEWSEQUENTIALID()"); // ordered GUIDs for clustered index performance

        // ━━ Columns ━━
        builder.Property(p => p.Name)
            .HasMaxLength(200)
            .IsRequired()
            .HasColumnName("ProductName");  // column name different from property name

        builder.Property(p => p.Price)
            .HasPrecision(18, 2)     // decimal(18,2) - ALWAYS set precision for money
            .IsRequired();

        builder.Property(p => p.Description)
            .HasMaxLength(4000)
            .IsRequired(false);     // nullable

        // ━━ Value objects / conversion ━━
        builder.Property(p => p.Slug)
            .HasMaxLength(250)
            .HasColumnType("varchar(250)");

        // ━━ Indexes - critical for query performance ━━
        builder.HasIndex(p => p.Slug).IsUnique();
        builder.HasIndex(p => new { p.CategoryId, p.Price }); // composite for filtered queries
        builder.HasIndex(p => p.CreatedAt);                   // for cursor pagination

        // ━━ Relationships ━━
        builder.HasOne(p => p.Category)
            .WithMany(c => c.Products)
            .HasForeignKey(p => p.CategoryId)
            .OnDelete(DeleteBehavior.Restrict); // never cascade delete products when category removed

        // ━━ Owned entity (value object in DDD) ━━
        builder.OwnsOne(p => p.Dimensions, dim =>
        {
            dim.Property(d => d.Width).HasColumnName("Width").HasPrecision(10, 2);
            dim.Property(d => d.Height).HasColumnName("Height").HasPrecision(10, 2);
            dim.Property(d => d.DepthCm).HasColumnName("Depth").HasPrecision(10, 2);
        });

        // ━━ Row version for optimistic concurrency ━━
        builder.Property<byte[]>("RowVersion")
            .IsRowVersion()
            .IsConcurrencyToken();

        // ━━ Soft delete ━━
        builder.Property(p => p.IsDeleted).HasDefaultValue(false);
        builder.HasQueryFilter(p => !p.IsDeleted); // global filter - never return deleted
    }
}

// Updated Product entity with owned entity
public class ProductDimensions { public decimal Width { get; set; } public decimal Height { get; set; } public decimal DepthCm { get; set; } }

// Extension to Product (simplified for compilation)
public static class ProductExtensions { public static string Slug(this Product p) => p.Name.ToLower(); }

Tip

Tip

Practice Fluent API Entity Configuration in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Fluent API Entity Configuration from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Fluent API Entity Configuration is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done