Entity Framework Core Interview Question #12
What is OnModelCreating?
EF Core Fundamentals & DbContext Junior Beginner
Quick Interview Answer
OnModelCreating is a DbContext method that can be overridden to configure the EF Core model with ModelBuilder.
Detailed Explanation
OnModelCreating is a DbContext method that can be overridden to configure the EF Core model with ModelBuilder.
It runs as EF Core builds the model and is commonly used to define relationships, indexes, constraints, property lengths, conversions, table names, default values, and seed configuration.
Large projects should avoid turning OnModelCreating into one enormous method; separate IEntityTypeConfiguration classes can keep mappings organized.
Code Example
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Product>()
.HasIndex(p => p.Slug)
.IsUnique();
}