📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you configure an EF Core model? Explain conventions, data annotations and the Fluent API with IEntityTypeConfiguration<T>, and how you set required properties and maximum lengths.

Covers EF Core model building: conventions, data annotations versus the Fluent API, IEntityTypeConfiguration<T>, ApplyConfigurationsFromAssembly, required and max length, and how nullable reference types affect the schema.

Junior Theory Beginner conventions data-annotations ef-core fluent-api model-configuration nullable-reference-types

🎯 Key points

  • Three layers: conventions → annotations → Fluent API (Fluent API wins)
  • Conventions: Id key, navigation + FK naming, NRT nullability
  • IEntityTypeConfiguration<T> + ApplyConfigurationsFromAssembly keeps OnModelCreating small
  • On SQL Server an unconfigured string maps to nvarchar(max); HasMaxLength(n) gives nvarchar(n)
  • nvarchar(max) cannot be an index key column (INCLUDE only), so no unique index or seek on it
  • IsRequired() or a non-nullable reference type → NOT NULL
  • ConfigureConventions for model-wide defaults (decimal precision, string length)
  • Every configuration change needs a new migration, reviewed before it is applied

⏱ 30-second answer

EF Core builds its model in three layers, each overriding the one before:

  • Conventions: a property named Id is the key, CustomerId plus a Customer navigation is a foreign key, and with nullable reference types on, string is NOT NULL and string? is NULL.
  • Data annotations: attributes like [MaxLength(200)], [Required], [Column] on the entity.
  • Fluent API: code in OnModelCreating, best split into one IEntityTypeConfiguration<T> class per entity and loaded with ApplyConfigurationsFromAssembly.

Always set HasMaxLength: on SQL Server an unconfigured string becomes nvarchar(max), which can only be an INCLUDE column, never an index key, so you lose seeks and unique constraints on it. Every change then goes through a reviewed migration. The trade-off: annotations are quick and visible; the Fluent API is more powerful and keeps the domain free of persistence attributes.

🗣 Full answer (senior)

How I would answer this in an interview

"EF Core builds a model of my entities before it can do anything, and it does that in three layers. First, conventions: a property called Id or OrderId becomes the primary key, a Customer navigation with a CustomerId property becomes a foreign key, and with nullable reference types enabled a string becomes NOT NULL while string? stays nullable. Second, data annotations such as [MaxLength] and [Required]. Third, the Fluent API in OnModelCreating, which overrides everything else and can express things annotations can't: composite keys, indexes with filters, value conversions, table splitting.

On real projects I keep the entities clean and put configuration in one IEntityTypeConfiguration<T> class per entity, then call modelBuilder.ApplyConfigurationsFromAssembly. That keeps OnModelCreating to a few lines and makes each table's mapping easy to review. For model-wide rules, like every decimal being decimal(18,2) or every string defaulting to 256, I use ConfigureConventions.

The mistake I see is leaving string lengths unconfigured. EF Core maps them to nvarchar(max), which can't be part of an index key, is stored off-row when large and makes memory grants bigger. So I always set HasMaxLength, and I treat the migration diff as the place to catch anything I forgot."


Precedence

Layer Example Wins over
Conventions Id → key; string (NRT on) → NOT NULL —
Data annotations [MaxLength(200)], [Required], [Table("Orders")] Conventions
Fluent API builder.Property(p => p.Name).HasMaxLength(200) Both

Annotations vs Fluent API

Data annotations Fluent API
Where On the entity IEntityTypeConfiguration<T>
Coverage Common cases Everything
Also used by ASP.NET Core validation EF Core only
Domain purity Adds attributes Keeps entities plain

Common settings

Need Fluent API Resulting SQL
Max length HasMaxLength(200) nvarchar(200)
Required IsRequired() NOT NULL
Non-Unicode IsUnicode(false) varchar
Decimal precision HasPrecision(18, 2) decimal(18,2)
Index HasIndex(x => x.Email).IsUnique() CREATE UNIQUE INDEX

Production example

On a customer table that grew to [5 million] rows, every string had defaulted to nvarchar(max). Adding HasMaxLength to the email column let us create a unique index on it, and a lookup that had been a 900 ms scan became a 2 ms seek.

🔍 What the interviewer is checking

Checks that the candidate can control the schema EF Core generates instead of accepting defaults.

Green flags

  • Knows the precedence order
  • Uses IEntityTypeConfiguration<T>
  • Mentions nvarchar(max) and indexing
  • Knows NRT drives nullability

Red flags

  • Has never seen the generated SQL types
  • Thinks annotations and Fluent API do unrelated things

📚 Learn in depth

1. How the model is built

ModelBuilder
  ├─ convention set runs (key discovery, relationship discovery, NRT nullability ...)
  ├─ data annotations applied (they are themselves conventions)
  ├─ OnModelCreating / IEntityTypeConfiguration<T>
  └─ model finalisation + validation  → IModel (cached)

Conventions are real objects (IConvention) that react to model changes, which is why adding a navigation in the Fluent API can trigger FK discovery.

2. Nullable reference types

With <Nullable>enable</Nullable>, EF Core reads nullability metadata: string Name is required, string? Notes is optional. This makes [Required] redundant for most properties, but the database is only as correct as your annotations: a string property initialised with = null! is still NOT NULL.

3. Pre-convention configuration

protected override void ConfigureConventions(ModelConfigurationBuilder b)
{
    b.Properties<decimal>().HavePrecision(18, 2);
    b.Properties<string>().HaveMaxLength(256);
}

This sets defaults for every property of a type; specific configuration still overrides it.

4. Why nvarchar(max) hurts

  • Cannot be an index key column (only an INCLUDE column).
  • Values over 8,000 bytes go to LOB pages.
  • The optimiser estimates memory grants from declared size, so wide columns inflate grants.

Try it yourself

  1. Create an entity with string, string? and decimal properties, add a migration with no configuration and read the generated column types.
  2. Add [MaxLength(100)], then override it to 200 in the Fluent API and confirm which wins.
  3. Move configuration into IEntityTypeConfiguration<T> classes and use ApplyConfigurationsFromAssembly.
  4. Add ConfigureConventions defaults and check the migration diff.

💻 Code

Configuration in its own class, loaded from the assembly, with model-wide defaults.

namespace Shop.Infrastructure;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

public sealed class Product
{
    public int Id { get; set; }
    public required string Name { get; set; }   // NRT: NOT NULL
    public string? Description { get; set; }     // NULL
    public required string Sku { get; set; }
    public decimal Price { get; set; }
}

public sealed class ProductConfiguration : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Products");
        builder.Property(p => p.Name).HasMaxLength(200);
        builder.Property(p => p.Description).HasMaxLength(2000);
        builder.Property(p => p.Sku).HasMaxLength(32).IsUnicode(false); // varchar(32)
        builder.HasIndex(p => p.Sku).IsUnique();
    }
}

public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options)
{
    public DbSet<Product> Products => Set<Product>();

    protected override void ConfigureConventions(ModelConfigurationBuilder b)
    {
        b.Properties<decimal>().HavePrecision(18, 2); // no more silent truncation warnings
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder) =>
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(ShopDbContext).Assembly);
}
CREATE TABLE [Products] (
    [Id] int NOT NULL IDENTITY,
    [Name] nvarchar(200) NOT NULL,
    [Description] nvarchar(2000) NULL,
    [Sku] varchar(32) NOT NULL,
    [Price] decimal(18,2) NOT NULL,
    CONSTRAINT [PK_Products] PRIMARY KEY ([Id])
);
CREATE UNIQUE INDEX [IX_Products_Sku] ON [Products] ([Sku]);

⚠ Common mistakes

  • Mistake: Leaving strings unconfigured. Why it is wrong: on SQL Server they become nvarchar(max), which cannot be an index key column, so no seek or unique index is possible. Instead: HasMaxLength on every string, or a convention default.
  • Mistake: Putting all configuration in one huge OnModelCreating. Why it is wrong: hard to review and merge. Instead: one IEntityTypeConfiguration<T> per entity.
  • Mistake: Relying on [Required] while nullable reference types are off. Why it is wrong: nullability becomes inconsistent across entities. Instead: enable NRT and let it drive nullability.
  • Mistake: Silencing warnings with public string Name { get; set; } = null!; and assuming the value is checked. Why it is wrong: the column is NOT NULL, but nothing in C# stops you saving a null; you get a DbUpdateException from SQL Server at run time. Instead: use required members or constructors so the compiler enforces it.
  • Mistake: Mixing annotations and Fluent API for the same property with different values. Why it is wrong: the Fluent API silently wins, and readers trust the attribute. Instead: choose one style per project.
  • Mistake: Ignoring the decimal precision warning. Why it is wrong: values can be silently truncated. Instead: HasPrecision or a convention.
  • Mistake: Changing configuration without adding and reviewing a migration. Why it is wrong: the model and the database drift, and EF Core 9+ throws a pending model changes error on Migrate(). Instead: dotnet ef migrations add after every change and review the diff like code.

🏛 Senior insight: trade-offs

Model configuration is schema design in C#. The senior habit is to treat the generated migration as the artefact you review, and to set project-wide defaults with ConfigureConventions so juniors can't forget string lengths or decimal precision.

Style When it fits Cost When not to
Conventions only Prototypes Wide columns, surprises Production schemas
Data annotations Small apps, shared validation Persistence attributes in the domain DDD domain models
Fluent API per entity Most production apps More files —

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions repeating HasMaxLength or HasPrecision everywhere. Why: Checks knowledge of pre-convention configuration.
    How to answer

    Override ConfigureConventions(ModelConfigurationBuilder configurationBuilder) on your DbContext. It is a separate override from OnModelCreating and runs before it, so model building starts with your defaults: configurationBuilder.Properties<decimal>().HavePrecision(18, 2) and configurationBuilder.Properties<string>().HaveMaxLength(256) apply to every property of that type, and Properties<Money>().HaveConversion<MoneyConverter>() registers a converter once. Anything you configure explicitly in OnModelCreating or with attributes overrides the default. For rules a type filter cannot express, add a custom convention with configurationBuilder.Conventions.Add(...). Because the defaults change column types, the next migration will alter existing columns: review it for truncation, and check the snapshot in a test so a changed convention never slips through silently.

  2. When: Candidate mentions default string mapping. Why: Checks the link between EF configuration and SQL Server behaviour.
    How to answer

    An nvarchar(max) column cannot be a key column of a B-tree index (clustered or non-clustered); it can only sit in INCLUDE or a full-text index, so a lookup on it scans. Values that do not fit in the row (over 8,000 bytes) move to LOB pages, so reading them costs extra I/O, and online index operations were historically restricted. The optimiser also estimates row size from the declared type, assuming a max column is about half-full of a large value, so sorts and hash joins get oversized memory grants that waste memory and reduce concurrency. EF Core maps an unconfigured string to nvarchar(max), so the fix is to give strings realistic lengths with HasMaxLength, a convention, or [MaxLength], and keep max for genuine documents.

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me