skip to content

DbContext & Modeling

How an EF Core model is built: the DbContext and its options, conventions versus the fluent API, owned and complex types, and inheritance. Interviewers probe it because mapping choices outlive code.

part ofEntity Framework Coreread it →
on this pageshow

explore

questions

22

In EF Core 10, what do the [Key], [Required], [MaxLength], [Column] and [Index] attributes change in the model, and what do conventions decide without them?

level: juniorimportance: must knowfreq 68%

answer

  1. Id or <Type>Id becomes the key
  2. nullable reference types decide required
  3. string: text on Npgsql, nvarchar(max) on SQL Server
  4. [Index] sits on the class
  5. two [Key] attributes throw

basics

~20 s

By convention EF Core makes a property named Id or <Type>Id the key, takes nullability from the C# type, maps strings without a length and names the table after the DbSet. [Key], [Required], [MaxLength], [Column] and [Index] override those choices.

solid answer

~40 s

Conventions pick the primary key from a property named `Id` or `<TypeName>Id` (case-insensitive), make non-nullable reference types required when nullable reference types are enabled, map a `string` to an unbounded type (`text` on Npgsql, `nvarchar(max)` on SQL Server), and name the table after the `DbSet<T>` property. `[Key]` picks another key property; `[Required]` makes a column `NOT NULL`; `[MaxLength(120)]` bounds it, so Npgsql emits `character varying(120)`; `[Column("TTL_NM", TypeName = ...)]` sets the column name, store type or order; and `[Index(nameof(AuthorId), nameof(PublishedOn), IsUnique = true)]` goes on the class and declares a single or composite index. `[Key]`, `[Required]` and `[MaxLength]` live in `System.ComponentModel.DataAnnotations`, `[Column]` in its `.Schema` namespace, and `[Index]` in `Microsoft.EntityFrameworkCore`. Two `[Key]` attributes throw; a composite key needs `[PrimaryKey]` or `HasKey`.

code

sql · 9 lines
sql
CREATE TABLE "BK_TITLES" (
    "TTL_NO" integer GENERATED BY DEFAULT AS IDENTITY,
    "TTL_NM" character varying(200) NOT NULL,
    "AUTH_ID" integer NOT NULL,
    "PUB_DT" date NOT NULL,
    CONSTRAINT "PK_BK_TITLES" PRIMARY KEY ("TTL_NO")
);

CREATE INDEX "IX_TITLES_AUTH_PUB" ON "BK_TITLES" ("AUTH_ID", "PUB_DT");

go deeper

for a junior

Recall the key-naming convention, what each of the five attributes changes, and that [Index] goes on the class.

for a middle

Explain how nullable reference types drive required columns, how provider type mappings change with [MaxLength], and why two [Key] attributes throw.

for a senior

Show how to map a legacy schema with odd names and lengths precisely, and how to confirm the inferred model with ToDebugString before migrating.

for a principal

Set a team policy on attributes versus fluent configuration so domain classes and schema rules stay readable as the model grows.

## What conventions decide on their own EF Core builds its **model** (the metadata describing tables, columns, keys and indexes) by running **conventions** over your entity classes. For a legacy bookstore entity with no attributes at all, the main defaults are: | Aspect | Convention | Where it comes from | |---|---|---| | Primary key | A property named `Id` or `<TypeName>Id`, compared case-insensitively | `KeyDiscoveryConvention` | | Table name | The name of the `DbSet<T>` property, otherwise the class name | `TableNameFromDbSetConvention` | | Column name | The property name | relational defaults | | Required or optional | Non-nullable value types and, with nullable reference types enabled, non-nullable reference types are required | `NonNullableReferencePropertyConvention` | | String length | Unbounded: `text` with Npgsql, `nvarchar(max)` with SQL Server | provider type mapping | | Key value generation | An integer key is store-generated; Npgsql uses an identity column by default | provider conventions | You can print the result with `context.Model.ToDebugString()` to see exactly what EF inferred before you start overriding it. ## What each attribute changes **Data annotations** are attributes on the entity class that override conventions for one property or class. - **`[Key]`** (`System.ComponentModel.DataAnnotations`) marks the key property when its name does not follow the `Id` pattern, for example `TitleNo`. - **`[Required]`** (same namespace) makes the column `NOT NULL`. It matters most for reference types when nullable reference types are off, or to make a `string?` property required in the database anyway. - **`[MaxLength(n)]`** (same namespace) bounds a string or byte array. Npgsql then maps a string to `character varying(n)`; SQL Server to `nvarchar(n)`. EF also honours `[StringLength(n)]`. - **`[Column]`** (`System.ComponentModel.DataAnnotations.Schema`) sets the **column name** (`[Column("TTL_NM")]`), the **store type** (`TypeName = "numeric(10,2)"`) and the **column order** used when a migration creates the table. Its sibling `[Table("BK_TITLES", Schema = "legacy")]` names the table. - **`[Index]`** (`Microsoft.EntityFrameworkCore`, from the `Microsoft.EntityFrameworkCore.Abstractions` package) goes on the **class**, not a property, and takes property names: `[Index(nameof(AuthorId), nameof(PublishedOn), IsUnique = true, Name = "IX_BK_TITLES_AUTH_PUB")]` declares a composite unique index. `IsDescending` or `AllDescending` set sort order. ## Composite keys are the exception Putting `[Key]` on two properties does **not** create a composite key. When the model is finalised EF throws `InvalidOperationException`: the entity "has multiple properties with the [Key] attribute", and the message suggests the class-level **`[PrimaryKey(nameof(StoreId), nameof(TitleId))]`** attribute or `HasKey` in `OnModelCreating`. A key configured explicitly with `HasKey` takes precedence over the attributes. ## Mapping a legacy table with attributes ```csharp [Table("BK_TITLES")] [Index(nameof(AuthorId), nameof(PublishedOn), Name = "IX_TITLES_AUTH_PUB")] public class Title { [Key, Column("TTL_NO")] public int TitleNo { get; set; } [Required, MaxLength(200), Column("TTL_NM")] public string Name { get; set; } = ""; [Column("AUTH_ID")] public int AuthorId { get; set; } [Column("PUB_DT", TypeName = "date")] public DateOnly PublishedOn { get; set; } } ``` ## Reading the inferred model before overriding it Mapping an existing schema starts with seeing what EF guessed. `context.Model.ToDebugString()` prints each entity type with its properties, their nullability, the primary key, indexes and annotations such as maximum length and column name. For the bookstore, three findings are typical: - a key such as `TitleNo` that the `Id` convention missed, so EF reports that the entity type requires a primary key; - string columns the legacy schema bounds at 40 or 200 characters that EF would create as unbounded; - columns with names like `TTL_NM` that no property name matches. Each finding maps to one attribute: `[Key]`, `[MaxLength]`, `[Column]`. After adding them, generate a migration against an empty database, or compare the debug output again, to confirm the model now matches the real tables before any code reads from them. ## What attributes cannot do Attributes cover the common cases, but some configuration has no attribute and needs the **fluent API** in `OnModelCreating`, for example an index filter (`HasFilter`), most relationship details beyond `[ForeignKey]` and `[InverseProperty]`, or table splitting. Attributes are also overridden by the fluent API when both configure the same thing, so a team that mixes them should know which one wins. ## Pitfalls interviewers probe 1. **Turning off nullable reference types changes the schema.** The same `string Name` becomes nullable when the project disables them, so the next migration alters the column. 2. **`[Required]` is shared with MVC validation.** On an entity used directly as a request model it also triggers model validation, which is a reason to keep request DTOs separate. 3. **Unbounded strings everywhere.** Without `[MaxLength]`, every string becomes `text` or `nvarchar(max)`, which a legacy schema with `varchar(40)` columns will not match. 4. **`[Index]` on a property does not compile**: the attribute is declared for classes.

  • How do you see what EF Core actually inferred for an entity before writing any attributes?
    Call `context.Model.ToDebugString()`, or `ToDebugString(MetadataDebugStringOptions.LongDefault)` for more detail. It prints every entity type with its properties, nullability, keys, indexes and annotations, so you can check which property became the key and which columns are unbounded before adding a migration.
  • Does [MaxLength] on an entity property validate input in a Minimal API endpoint?
    Not by itself. For EF Core it is a mapping attribute that sets the column length; EF does not validate values against it before saving, and the database rejects or truncates according to its own rules. Request validation is a separate ASP.NET Core concern, usually done on a request DTO.

  • Putting [Key] on two properties gives an entity a composite primary key.
  • [Index] is placed on the property it indexes.
  • A string property gets nvarchar(255) by default.
  • [Column] can only rename a column; the type always comes from the CLR type.
  • EF Core requires every key property to be called Id.
open as a page

In EF Core 10, what do a DbContext and its DbSet<T> properties do, and when does a change actually reach the database?

level: juniorimportance: must knowfreq 74%

basics

~20 s

A DbContext is EF Core's session with a database: it owns the model, tracks entities and turns their changes into SQL. Each DbSet<T> is the query root for one entity type. Nothing is written until SaveChanges or SaveChangesAsync runs.

open as a page

In EF Core 10, how does an abstract Payment class with CardPayment, BankTransferPayment and VoucherPayment subclasses map to tables by default?

level: juniorimportance: must knowfreq 50%

basics

~20 s

By default EF Core uses table-per-hierarchy (TPH): every payment type goes into one Payments table, with a shadow Discriminator column holding the class name, such as CardPayment, and nullable columns for each subclass's properties. Subclasses must be added to the model explicitly.

open as a page

In EF Core 10, how is an OrderStatus enum property stored by default, and how do you store its name with HasConversion<string>()?

level: juniorimportance: must knowfreq 52%

basics

~20 s

EF Core stores an enum as its underlying integer type by default, so a plain OrderStatus becomes an int column. HasConversion<string>() picks the built-in enum-to-string converter and the column holds names such as "Shipped"; add HasMaxLength so the column is not unbounded.

open as a page

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?

level: middleimportance: must knowfreq 62%

basics

~20 s

The 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.

open as a page

In EF Core, why does one DbContext shared by concurrent work fail under load, and what does EF throw when it detects the overlap?

level: middleimportance: must knowfreq 66%

basics

~20 s

A DbContext is not thread-safe: its change tracker, connection and transaction state assume one operation at a time. When a second operation starts before the first completes, EF throws InvalidOperationException; when the overlap goes undetected, results and tracked state can be corrupted.

open as a page

In EF Core 10, when do you map a value object such as an Address with ComplexProperty rather than OwnsOne, and what behaves differently?

level: middleimportance: must knowfreq 58%

basics

~20 s

Use ComplexProperty for a keyless value object such as an Address or a Money amount: complex types have value semantics, no hidden key and may be structs. Keep OwnsOne or OwnsMany for what complex types cannot do: a separate table or a navigation to an entity.

open as a page

In EF Core 10, what SQL do db.Payments and db.Payments.OfType<CardPayment>() send under TPH, TPT and TPC, and which strategy suits which query pattern?

level: seniorimportance: must knowfreq 45%

basics

~20 s

TPH reads one table, adding a discriminator filter for OfType<CardPayment>(). TPT joins the base table to every subtype table and computes the type with CASE. TPC unions every concrete table, and OfType narrows that to the CardPayments table. TPH suits mixed-type reads; TPC suits single-type reads.

open as a page

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%

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.

open as a page

With the dotnet-ef tool, what does dotnet ef dbcontext scaffold generate from an existing database, and which options and habits keep a re-scaffold from destroying your changes?

level: middleimportance: should knowfreq 42%

basics

~20 s

dotnet ef dbcontext scaffold reads a database schema and writes partial entity classes plus a partial DbContext configured with the fluent API. Edits survive a re-scaffold only in separate partial files or OnModelCreatingPartial, because --force overwrites generated files.

open as a page

In EF Core, how does configuring a DbContext in OnConfiguring differ from passing DbContextOptions<TContext> to its constructor, and can the two be combined?

level: middleimportance: should knowfreq 44%

basics

~20 s

Constructor options are built outside the context, by DI or a DbContextOptionsBuilder<TContext>, and passed in; OnConfiguring builds them inside the class. OnConfiguring still runs when options were passed, so the two combine, and IsConfigured tells it a provider is already set.

open as a page

In EF Core 10, how do you rename and re-value a TPH discriminator with HasDiscriminator and HasValue, and what does IsComplete(false) change?

level: middleimportance: should knowfreq 40%

basics

~20 s

Call HasDiscriminator<string>("PaymentType") on the root entity and chain HasValue<CardPayment>("card") for each type, or point HasDiscriminator at a CLR property such as an enum. IsComplete(false) makes EF Core filter even base-type queries to the known values.

open as a page

In EF Core 10, what tables do UseTptMappingStrategy and UseTpcMappingStrategy create for a Payment hierarchy, and how do the schemas differ?

level: middleimportance: should knowfreq 42%

basics

~20 s

Both are called on the root entity. TPT creates a Payments table for base columns plus a table per subclass whose key is also a foreign key to Payments. TPC creates one complete table per concrete class, repeating the base columns, and none for an abstract Payment.

open as a page

In EF Core 10, how is a List<string> of finishes on a Product mapped without configuration, and how do queries over it translate?

level: middleimportance: should knowfreq 40%

basics

~20 s

Since EF Core 8, a public read-write List<string> on an entity is a primitive collection: SQL Server stores it as a JSON array in one string column, and Npgsql uses a native PostgreSQL array. Contains, Any and Count on it translate to SQL.

open as a page

In EF Core, how do backing fields let an entity expose a read-only property or collection, and what does PropertyAccessMode change about how EF reads and writes it?

level: seniorimportance: should knowfreq 36%

basics

~20 s

A backing field is the field EF Core reads and writes instead of the property, found by convention (_name) or named with HasField or [BackingField]. In the default PreferField mode EF bypasses getters and setters, so properties can be read-only or validated.

open as a page

In EF Core, what is a shadow property, how do you configure, set and query one, and when does EF create one without being asked?

level: seniorimportance: should knowfreq 38%

basics

~20 s

A shadow property is a column EF Core maps without a matching CLR property: it exists in the model and its value lives in the change tracker. Configure it with Property<T>("Name"), set it through Entry(...).Property("Name"), and query it with EF.Property<T>.

open as a page

In EF Core, when should code take an IDbContextFactory<TContext> instead of an injected context, and what does AddPooledDbContextFactory register and change?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Take IDbContextFactory<TContext> when the code's lifetime does not match one context: singletons, background jobs, parallel branches, long-lived UI sessions. The caller creates and disposes each context. AddPooledDbContextFactory backs the factory with a context pool and also registers a scoped TContext.

open as a page

In EF Core 10, what does AddDbContextPool reuse, what does its poolSize of 1024 actually limit, and what does returning a context to the pool reset?

level: seniorimportance: should knowfreq 40%

basics

~20 s

AddDbContextPool reuses DbContext instances to skip their setup cost. poolSize, 1024 by default, caps how many idle instances are kept, not concurrency. On return EF clears tracking, transactions and owned connections and restores startup settings, but not your own fields.

open as a page

In EF Core 10, why can't a TPC payment hierarchy use an ordinary identity column per table, and how does EF Core generate its keys instead?

level: seniorimportance: should knowfreq 30%

basics

~20 s

EF Core requires keys unique across a whole hierarchy, but under TPC each concrete type has its own table, so separate identity columns would each start at 1 and collide. SQL Server and Npgsql therefore default integer TPC keys to one shared database sequence, such as PaymentSequence.

open as a page

In EF Core 10, how do you map an order's delivery address and price adjustments to JSON columns, and how do LINQ filters on them translate?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Call ToJson on a complex property or complex collection: ComplexProperty(o => o.DeliveryAddress, b => b.ToJson()). EF Core 10 stores each in one JSON column and translates filters on members into JSON path SQL, such as the ->> operator on PostgreSQL's jsonb or JSON_VALUE on SQL Server.

open as a page

In EF Core 10, how do you map a strongly typed OrderId record struct as a primary and foreign key, and what stops working?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Give OrderId a ValueConverter<OrderId, int>, ideally once in ConfigureConventions so the key and every foreign key share it, and call ValueGeneratedOnAdd if the database should generate ids. Queries must compare whole OrderId values; members such as o.Id.Value do not translate.

open as a page

In EF Core 10, what do the three expressions passed to ValueComparer<T> do, and when must a HasConversion property supply one?

level: seniorimportance: nice to knowfreq 26%

basics

~20 s

A ValueComparer<T> holds an equality expression, a hash-code expression and a snapshot expression. A HasConversion property needs one when its type is a mutable reference type, because EF Core otherwise snapshots the same instance and misses edits made in place.

open as a page