skip to content

In EF Core, what does overriding ConfigureConventions let you do, such as capping every string's length or removing a built-in convention, that OnModelCreating does not?

level: middleimportance: should knowfreq 34%

answer

  1. runs before model building
  2. Properties<string>().HaveMaxLength(500)
  3. overrides annotations, loses to fluent
  4. Conventions.Remove / Add / Replace
  5. IgnoreAny<T>()

basics

~20 s

ConfigureConventions runs before the model is built and sets rules per CLR type, such as Properties<string>().HaveMaxLength(500), applied to every matching property as it is discovered. It can also add, remove or replace conventions, which OnModelCreating cannot.

solid answer

~30 s

`ConfigureConventions(ModelConfigurationBuilder configurationBuilder)` runs before `OnModelCreating`, when EF builds the model. `configurationBuilder.Properties<string>().HaveMaxLength(500)` or `Properties<decimal>().HavePrecision(10, 2)` applies to every property of that type as it enters the model, including foreign keys and shadow properties, which a loop in `OnModelCreating` can miss. `IgnoreAny<T>()` keeps a type out of the model and `DefaultTypeMapping<T>()` sets the mapping used for constants of a type. `configurationBuilder.Conventions` lets you `Remove`, `Add` or `Replace` model-building conventions, such as removing `TableNameFromDbSetConvention`. Pre-convention configuration counts as explicit: it overrides conventions and data annotations, so a type-wide length beats `[MaxLength]`, while fluent calls in `OnModelCreating` still override it.

code

csharp · 12 lines
csharp
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
{
    // every string is varchar(500) unless OnModelCreating says otherwise
    configurationBuilder.Properties<string>().HaveMaxLength(500);
    configurationBuilder.Properties<decimal>().HavePrecision(10, 2);

    // tables named after the entity class, not the DbSet property
    configurationBuilder.Conventions.Remove<TableNameFromDbSetConvention>();
}

protected override void OnModelCreating(ModelBuilder modelBuilder)
    => modelBuilder.Entity<Title>().Property(t => t.Isbn).HasMaxLength(13); // wins over 500

go deeper

for a junior

Recall that ConfigureConventions is a DbContext override for type-wide rules such as a default string length.

for a middle

Explain how pre-convention configuration ranks against conventions, data annotations and fluent calls, with the [MaxLength] surprise.

for a senior

Choose between pre-convention configuration, a finalizing convention and removing a built-in convention, and verify the effect on the model and the next migration.

for a principal

Decide which schema rules belong in shared conventions for all contexts and which stay explicit per entity, so the model remains predictable.

## Where ConfigureConventions runs When EF Core builds a context's model for the first time, it creates a `ModelConfigurationBuilder`, calls your **`ConfigureConventions`** override with it, and only then creates the `ModelBuilder` and calls **`OnModelCreating`**. The model is cached afterwards, so both run once per context type, not per instance. That ordering gives `ConfigureConventions` two powers `OnModelCreating` lacks: - **pre-convention configuration**: rules declared per CLR type before any entity is discovered; - **control over the convention set**: adding, removing and replacing the conventions that build the model. ## Pre-convention configuration For a legacy bookstore database where every text column is `varchar(500)` and every price `numeric(10,2)`: ```csharp protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { configurationBuilder.Properties<string>().HaveMaxLength(500); configurationBuilder.Properties<decimal>().HavePrecision(10, 2); configurationBuilder.IgnoreAny<IDomainEvent>(); } ``` The `Properties<TProperty>()` builder offers members such as: - `HaveMaxLength(int)`, `HavePrecision(int, int)`, `AreUnicode(bool)`; - `HaveColumnType(string)` from the relational package; - `HaveConversion<TConversion>()` for a type-wide value converter. Other entry points: - **`IgnoreAny<T>()`** keeps a type, including an interface, out of the model, as an entity and as a property type; - **`DefaultTypeMapping<T>()`** sets the mapping EF uses for constants of a type in queries that touch no property of it. The type given can be an interface, a base type, a generic type definition or an exact type. When several match, they apply from the least specific to the most specific: interface, base type, generic type definition, non-nullable value type, exact type. ### How it ranks against other configuration Pre-convention configuration is applied as **explicit** configuration the moment a matching property is added to the model. Consequences: | Competing configuration | Result | |---|---| | A convention, e.g. unbounded strings | Pre-convention wins | | A data annotation, e.g. `[MaxLength(40)]` | **Pre-convention wins** | | A fluent call in `OnModelCreating`, e.g. `HasMaxLength(40)` | The fluent call wins, because it runs later | The second row surprises people: a type-wide `HaveMaxLength(500)` turns a `[MaxLength(40)]` column into 500, and the documentation adds that string foreign keys get it too, even when that no longer matches their principal key. ## Changing the convention set `configurationBuilder.Conventions` is a `ConventionSetBuilder` with: 1. **`Remove(Type)`** / **`Remove<TImplementation>()`**: drop a built-in convention. Removing `TableNameFromDbSetConvention` makes tables take the entity class name instead of the `DbSet` property name; removing `ForeignKeyIndexConvention` stops EF creating an index for every foreign key. 2. **`Add(Func<IServiceProvider, IConvention>)`**: add your own convention class. 3. **`Replace<TImplementation>(...)`**: swap a built-in convention for a derived one. A **custom convention** is a class implementing interfaces such as `IModelFinalizingConvention`. Unlike pre-convention configuration it can filter on anything in the model, and it should configure through the convention builders so it never overrides data annotations or explicit configuration. The documentation's guidance: - use **pre-convention configuration** when the rule depends only on the CLR type and should override annotations; - use a **finalizing convention** when the rule is more complex or must let annotations win; - use **interactive conventions** when several conventions depend on each other. ## A worked legacy example A legacy bookstore schema on PostgreSQL stores all text as `varchar(500)`, all money as `numeric(10,2)`, and names tables after their entity classes. Without `ConfigureConventions`, every string property would need `HasMaxLength(500)`, every price `HavePrecision`, and every table a `ToTable` call. With it: - `Properties<string>().HaveMaxLength(500)` sets the common length once; - `Properties<decimal>().HavePrecision(10, 2)` covers prices, discounts and tax amounts; - removing `TableNameFromDbSetConvention` lets the class name decide the table name; - the handful of exceptions, such as a 13-character ISBN, stay as explicit fluent calls in `OnModelCreating` or an `IEntityTypeConfiguration<T>` class, where they win. Before adopting such rules on an existing database, scaffold or migrate against a copy and compare: a type-wide rule that disagrees with one real column becomes an unwanted `ALTER COLUMN` in the next migration. ## Limits - Pre-convention configuration selects by CLR type only; it cannot target "every property named `CreatedAt`". - Many aspects cannot be configured this way. - An error raised while applying it does not show `ConfigureConventions` in the stack trace, which makes conflicts harder to trace. - It applies to every context type that inherits the override, so a shared base context spreads the rule to models that may not want it. - Removing a convention changes the whole model; check `context.Model.ToDebugString()` and the next migration's diff before keeping it.

  • How would you give every string a default length but still let [MaxLength] on a property win?
    Use a custom finalizing convention instead of pre-convention configuration: implement `IModelFinalizingConvention`, loop over string properties and set the length through the convention builder, which refuses to override data-annotation or explicit configuration. Register your convention class in `ConfigureConventions` with `configurationBuilder.Conventions.Add(_ => new MaxStringLengthConvention())`, where `MaxStringLengthConvention` is the class you wrote.
  • Why not just loop over modelBuilder.Model.GetEntityTypes() in OnModelCreating to set string lengths?
    That metadata loop only sees what exists when it runs, so properties added later, such as shadow foreign keys created by relationship conventions, can be missed, and every change must be made explicitly. Pre-convention configuration applies whenever a matching property is added, at any point during model building.

  • ConfigureConventions runs on every new context instance.
  • [MaxLength] on a property overrides Properties<string>().HaveMaxLength.
  • Pre-convention configuration also overrides fluent calls in OnModelCreating.
  • Removing a convention affects only the entity types you configure explicitly.
  • Properties<T>() can select properties by name as well as by type.