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?
answer
- Id or <Type>Id becomes the key
- nullable reference types decide required
- string: text on Npgsql, nvarchar(max) on SQL Server
- [Index] sits on the class
- two [Key] attributes throw
basics
~20 sBy 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 sConventions 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 linesCREATE 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
Recall the key-naming convention, what each of the five attributes changes, and that [Index] goes on the class.
Explain how nullable reference types drive required columns, how provider type mappings change with [MaxLength], and why two [Key] attributes throw.
Show how to map a legacy schema with odd names and lengths precisely, and how to confirm the inferred model with ToDebugString before migrating.
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.