In EF Core, when a convention, a data annotation and the fluent API configure one property differently, which wins, and where do IEntityTypeConfiguration<T> classes fit?
answer
- Explicit > DataAnnotation > Convention
- last fluent call wins
- Configure(EntityTypeBuilder<T> builder)
- ApplyConfigurationsFromAssembly needs a parameterless ctor
- [EntityTypeConfiguration<TConfig, TEntity>]
basics
~20 sThe fluent API wins over data annotations, which win over conventions; among fluent calls the last one wins. IEntityTypeConfiguration<T> is the same fluent API moved into one class per entity and applied from OnModelCreating, so it has fluent precedence.
solid answer
~40 sEF Core tracks where each piece of configuration came from: explicit fluent API calls beat data annotations, which beat conventions, so `HasMaxLength(80)` overrides `[MaxLength(200)]`, which overrides the unbounded default. Fluent calls are applied in order, so a later call on the same property replaces an earlier one. `IEntityTypeConfiguration<TEntity>` moves an entity's fluent configuration into its own class with a `Configure(EntityTypeBuilder<TEntity> builder)` method; `modelBuilder.ApplyConfiguration(new TitleConfiguration())` or `ApplyConfigurationsFromAssembly(...)` runs it inside `OnModelCreating`, so it carries fluent precedence. Assembly scanning only instantiates classes with a parameterless constructor and its order is documented as undefined, so two classes must not configure the same thing. `[EntityTypeConfiguration<TitleConfiguration, Title>]` on the entity links them without scanning; that generic form arrived in EF Core 8.
code
csharp · 14 linespublic class BookstoreContext(DbContextOptions<BookstoreContext> options) : DbContext(options)
{
public DbSet<Title> Titles => Set<Title>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(
typeof(BookstoreContext).Assembly,
t => t.Namespace == "Bookstore.Data.Configurations");
// runs after the scan, so it overrides TitleConfiguration's 200
modelBuilder.Entity<Title>().Property(t => t.Name).HasMaxLength(250);
}
}go deeper
Recall the order: fluent API over data annotations over conventions, and that the last fluent call wins.
Explain IEntityTypeConfiguration<T>, the three ways to apply it, and the parameterless-constructor rule of ApplyConfigurationsFromAssembly.
Show how mixed attributes, configuration classes and later OnModelCreating calls interact on a legacy schema, and how to avoid order-dependent configuration.
Decide a project-wide configuration style, weighing persistence-free domain classes against configuration living next to the properties it describes.
## Three sources, one winner Every element of an EF Core model remembers **where its configuration came from**, recorded as a `ConfigurationSource` value: | Source | How it is written | Precedence | |---|---|---| | `Explicit` | Fluent API calls in `OnModelCreating` (including `IEntityTypeConfiguration<T>` classes) | Highest | | `DataAnnotation` | Attributes such as `[MaxLength]`, `[Column]`, `[Required]` | Middle | | `Convention` | EF Core's built-in conventions | Lowest | A source can only be overridden by an equal or higher one. So, for a legacy `Title.Name` property: - convention: unbounded `text`; - `[MaxLength(200)]` on the property: `character varying(200)`; - `builder.Property(t => t.Name).HasMaxLength(80)` in fluent code: `character varying(80)`, whatever the attribute says. **Among fluent calls, the last call wins.** Configuring the same property twice in `OnModelCreating` leaves the later value. Pre-convention configuration in `ConfigureConventions` counts as explicit too, so it overrides attributes and conventions, but fluent calls in `OnModelCreating` run after it and override it in turn. ## IEntityTypeConfiguration<T>: organisation, not a new layer A model for a large legacy schema makes `OnModelCreating` hundreds of lines long. **`IEntityTypeConfiguration<TEntity>`** splits it by entity: ```csharp public class TitleConfiguration : IEntityTypeConfiguration<Title> { public void Configure(EntityTypeBuilder<Title> builder) { builder.ToTable("BK_TITLES", "legacy"); builder.HasKey(t => t.TitleNo); builder.Property(t => t.TitleNo).HasColumnName("TTL_NO"); builder.Property(t => t.Name).HasColumnName("TTL_NM").HasMaxLength(200); builder.HasIndex(t => new { t.AuthorId, t.PublishedOn }) .HasDatabaseName("IX_TITLES_AUTH_PUB"); } } ``` The class uses exactly the same `EntityTypeBuilder<T>` the fluent API hands you in `OnModelCreating`, so its configuration is **explicit** and has fluent precedence. Nothing is applied until the context registers it. ## Three ways to apply configuration classes 1. **One at a time**: `modelBuilder.ApplyConfiguration(new TitleConfiguration());` in `OnModelCreating`. The order is the order of your calls, and you can pass constructor arguments. 2. **By assembly scan**: `modelBuilder.ApplyConfigurationsFromAssembly(typeof(BookstoreContext).Assembly);` finds every non-abstract `IEntityTypeConfiguration<T>` implementation. Points to remember: - it only instantiates types with a **parameterless constructor**, public or not; others are skipped and EF logs `SkippedEntityTypeConfigurationWarning`; - an optional `predicate` filters the types, useful when one assembly holds configurations for two contexts; - the documentation calls the **order undefined**, so two classes configuring the same property is a bug waiting to happen. 3. **By attribute on the entity**: `[EntityTypeConfiguration<TitleConfiguration, Title>]` on `Title`, or `[EntityTypeConfiguration(typeof(TitleConfiguration))]`. EF applies it whenever `Title` enters the model through a `DbSet<Title>` or another mapping. The attribute is **not** discovered by scanning an assembly; the entity must be part of the model first. Fluent calls written in `OnModelCreating` **after** the apply call override what the configuration classes set, which is a handy way to make one context differ from another sharing the same configuration classes. ## Precedence in a mixed legacy mapping Consider `Title.Name` in the bookstore model, configured in four places over time: 1. Convention: a non-nullable `string`, so required and unbounded. 2. Attribute: `[MaxLength(200)]` and `[Column("TTL_NM")]` on the property. 3. `TitleConfiguration`: `builder.Property(t => t.Name).HasMaxLength(120);` 4. `OnModelCreating`, after the scan: `modelBuilder.Entity<Title>().Property(t => t.Name).IsRequired(false);` The resulting column is named `TTL_NM` (only the attribute set a name), is 120 characters long (the configuration class outranks the attribute), and is nullable (the explicit `IsRequired(false)` outranks the nullable-reference-type convention). Each fact comes from the highest-ranked source that mentioned it; sources that say nothing about a facet do not reset it. ## Choosing a style - **Attributes** keep simple facts next to the property and are visible to other libraries, but they put database detail into domain classes and cannot express everything. - **Fluent API in configuration classes** keeps entity classes free of persistence detail, covers every feature and is the usual choice for a legacy schema whose names and indexes do not follow conventions. - **Mixing** is legal, but every mixed property is a precedence puzzle for the next reader, so many teams pick one style per project. ## Pitfalls - Expecting an attribute to win because it sits on the property: a fluent call silently overrides it. - Adding a constructor parameter to a configuration class and losing it from the assembly scan without noticing the warning. - Relying on scan order when two configuration classes touch the same entity. - Forgetting the `ApplyConfiguration...` call entirely: the class compiles and is never used. - Debugging the wrong layer: when a column comes out unexpectedly, `context.Model.ToDebugString()` shows the final value, and searching the configuration classes, the attributes and `ConfigureConventions` in precedence order finds its source quickly.
- Does pre-convention configuration in ConfigureConventions override a [MaxLength] attribute?Yes. Configuration set in `ConfigureConventions`, such as `Properties<string>().HaveMaxLength(256)`, is applied as explicit configuration when a matching property is added, so it overrides conventions and data annotations. Fluent calls in `OnModelCreating` still override it, because they are explicit too and run later.
- Why might ApplyConfigurationsFromAssembly skip a configuration class silently?It only instantiates classes that have a parameterless constructor, public or non-public. A class whose only constructor takes parameters is skipped, and EF logs `SkippedEntityTypeConfigurationWarning` rather than throwing. Apply such classes yourself with `modelBuilder.ApplyConfiguration(new TitleConfiguration(schema))`.
- A data annotation on the property always beats the fluent API.
- IEntityTypeConfiguration<T> classes are applied automatically without any call.
- ApplyConfigurationsFromAssembly applies classes in a guaranteed declaration order.
- When two fluent calls conflict, EF throws at model building.
- [EntityTypeConfiguration] attributes are discovered by scanning the assembly.
Assumes EF Core 10; the generic EntityTypeConfigurationAttribute<TConfiguration, TEntity> was added in EF Core 8, while earlier versions use [EntityTypeConfiguration(typeof(...))].