Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 41 ยท DbContext and Models

Entity Classes and Conventions

Learn the EF Core model-building conventions - table and column names, primary keys, nullability, type mapping and navigation properties - and how to design clean entity classes.

You rarely have to tell EF Core everything. When it builds the model it applies conventions: sensible default rules that turn your classes into tables, your properties into columns and your navigation properties into relationships. If your classes follow the conventions, you can write very little configuration. If a default is wrong for you, you override just that part with annotations or the fluent API (next lesson).

Knowing the conventions well saves you from two common mistakes: configuring things EF Core would do anyway, and being surprised by what it did without being asked.

The main conventions

Given this entity and context:

C#
public class Product
{
    public int Id { get; set; }                    // primary key
    public string Name { get; set; } = "";         // required, non-nullable string
    public string? Description { get; set; }       // optional, nullable column
    public decimal Price { get; set; }
    public DateTime CreatedAt { get; set; }
    public bool IsActive { get; set; }
    public int CategoryId { get; set; }            // foreign key by name
    public Category Category { get; set; } = null!; // navigation to the principal
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public List<Product> Products { get; set; } = new();   // collection navigation
}

EF Core concludes:

  • Table name: the name of the DbSet<T> property (Products), or the class name if there is none. Providers may pluralize or not.
  • Column names: the property names.
  • Primary key: a property named Id or <ClassName>Id (case-insensitive).
  • Nullability: with nullable reference types enabled, string is NOT NULL and string? is NULL. Value types such as int and decimal are NOT NULL; int? is nullable.
  • Relationship: Product.CategoryId plus the Category navigation (and the inverse Products) is one-to-many. The foreign key is found by name: <NavigationName>Id or <PrincipalClass>Id.
  • Types: intโ†’integer, stringโ†’text (for example nvarchar(max) on SQL Server), decimalโ†’a provider-specific decimal (with a warning if you do not set precision), DateTimeโ†’date-time, boolโ†’bit/boolean, enumsโ†’integers.
  • Discovery: types reachable from a DbSet<T> through navigations are added to the model automatically.

Convention over configuration

Id Becomes the primary key
string? Becomes a nullable column
CategoryId Becomes a foreign key
DbSet name Becomes the table name

Only configure what differs

1 / 2

Rules your classes must satisfy

An entity type needs some care to be materialized by EF Core:

  • It must have a constructor EF Core can call: a parameterless one (it may be private or protected), or a constructor whose parameters match property names so EF Core can bind them.
  • Mapped properties need a getter and, for normal mapping, a setter (it can be private or init).
  • Public fields are not mapped by default; use properties.
  • Navigation properties for collections should be initialized (= new()) so you never see null when adding.
C#
public class Review
{
    private Review() { }                       // for EF Core
    public Review(int productId, int stars)    // for your code
    {
        ProductId = productId;
        Stars = stars;
    }

    public int Id { get; private set; }
    public int ProductId { get; private set; }
    public int Stars { get; private set; }
}

Such "rich" entities protect their invariants: nobody outside can create a Review with a missing product.

Seeing what EF Core decided

The model can be printed so you do not have to guess:

C#
Console.WriteLine(db.Model.ToDebugString(MetadataDebugStringOptions.ShortDefault));

And you can check one property:

C#
var prop = db.Model.FindEntityType(typeof(Product))!.FindProperty(nameof(Product.Price))!;
Console.WriteLine(prop.GetColumnType());   // e.g. decimal(18,2) on SQL Server

When a column ends up with an unexpected type or length, this is where you look first.

Stand-in: a convention engine

The editor below is a stand-in, not EF Core. It reads a class by reflection and applies three conventions: the key, nullability and the foreign-key-by-name rule. It prints what it "decided".

C# Stand-in: apply EF-style conventions by reflection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You can edit Product: rename Id to ProductId and the key is still found; rename CategoryId to CatId and the foreign-key note disappears, just as EF Core would stop recognizing it.

Stand-in: naming strategies

Many teams want snake_case column names (common with PostgreSQL). EF Core has a community package for that, but the core idea is a function applied to every name:

C# Stand-in: a snake_case naming rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common mistakes

  • No key found: a class without Id or <Class>Id fails with "requires a primary key". Add a key or mark the type as keyless on purpose.
  • Unset decimal precision: EF Core warns that decimal has no configured precision, because values can be silently truncated. Configure it (next lesson).
  • Public fields: they are ignored; use properties.
  • Uninitialized collections: product.Tags.Add(...) throws a NullReferenceException if the collection is null.
  • Surprise table names: renaming a DbSet property renames the table, and a migration will drop and recreate or rename it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which property is picked up as the primary key of class Order by convention?

    A property named Id or <ClassName>Id (case-insensitive) becomes the key.
  2. 2. With nullable reference types on, what is the column for string? Notes?

    string? maps to a nullable column; string maps to NOT NULL.
  3. 3. How does EF Core normally find the foreign key for a navigation Product.Category?

    A property named after the navigation or the principal type plus Id is discovered as the foreign key.
  4. 4. Which of these is NOT mapped by default?

    EF Core maps properties, not fields, by default.

Summary

  • Conventions turn classes into tables, properties into columns and navigations into relationships.
  • Key = Id or <Class>Id; nullability follows C# nullable annotations; foreign keys are found by name.
  • Entities need a constructor EF Core can use and properties, not public fields.
  • db.Model.ToDebugString() shows what was decided.
  • Override only what differs from the convention.

Next: Data Annotations and the Fluent API