Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 41 ยท DbContext and Models

Keys and Generated Values

Learn EF Core primary keys, alternate keys, composite keys, identity columns, GUIDs, sequences, default values and computed columns, with the trade-offs of each key strategy.

Every entity that EF Core tracks needs a key: the value that identifies one row. The key decides how EF Core finds an entity again, how it links relationships, and how Find and Update work. Just as important is who creates the key: your code, the database, or the framework.

This lesson walks through the key strategies you will meet (integers, GUIDs, composite and alternate keys) and the other values the database can generate for you (defaults, computed columns, timestamps). Real EF Core code is read-only; stand-ins demonstrate key generation ideas you can run.

Primary keys

By convention a property named Id or <Class>Id is the primary key. You can also say it explicitly:

C#
// annotation
public class Customer { [Key] public int CustomerNumber { get; set; } }

// fluent API
modelBuilder.Entity<Customer>().HasKey(c => c.CustomerNumber);

An integer key is, by convention, generated by the database when you insert (an identity column on SQL Server, SERIAL/identity on PostgreSQL, AUTOINCREMENT on SQLite). After SaveChanges the property holds the generated value:

C#
var c = new Customer { Name = "Ada" };
db.Customers.Add(c);          // c.Id is 0 here: "no value yet"
await db.SaveChangesAsync();
Console.WriteLine(c.Id);      // the value the database generated

EF Core treats the CLR default (0) as "not set", which is why it knows to ask the database for a value.

Choosing a key type

Strategy Pros Cons
int / long identity Small, fast, readable, ordered Needs a database round trip, guessable ids in URLs, awkward to merge databases
Guid Created in your code before saving, hard to guess, merge-friendly 16 bytes, random values fragment clustered indexes (unless sequential)
Natural key (ISBN, country code) Meaningful Real-world values change and have exceptions
string slug Readable URLs Needs a uniqueness rule

For GUIDs, EF Core's SQL Server provider generates sequential GUIDs by default for key properties, which avoids index fragmentation. On other databases and in .NET 9 and later, Guid.CreateVersion7() gives time-ordered values created in your own code:

C#
public class Order
{
    public Guid Id { get; set; } = Guid.CreateVersion7();
}

A key you assign yourself needs ValueGeneratedNever() when EF Core would otherwise try to generate it:

C#
modelBuilder.Entity<Country>().Property(c => c.Code).ValueGeneratedNever();

Composite and alternate keys

A composite key uses several columns, typical for join tables. Use the fluent API (or the class-level [PrimaryKey("OrderId", "LineNumber")] attribute):

C#
modelBuilder.Entity<OrderLine>().HasKey(l => new { l.OrderId, l.LineNumber });

An alternate key is a unique, non-primary identifier that other entities can reference:

C#
modelBuilder.Entity<Customer>().HasAlternateKey(c => c.Email);

If you only need uniqueness without being a relationship target, a unique index is lighter: HasIndex(c => c.Email).IsUnique().

Other generated values

Keys are one case of ValueGenerated. EF Core supports several patterns:

C#
modelBuilder.Entity<Post>(e =>
{
    e.Property(p => p.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP");   // set by DB on insert
    e.Property(p => p.Slug).HasComputedColumnSql("lower(replace([Title], ' ', '-'))", stored: true);
    e.Property(p => p.Views).HasDefaultValue(0);
    e.Property(p => p.Version).IsRowVersion();                              // changes on every update
});
  • Default values apply only when you do not supply a value. A subtle trap: for a bool with HasDefaultValue(true), assigning false is the CLR default, so EF Core thinks "not set" and sends the database default. Use a nullable type or a sentinel when that matters.
  • Computed columns are calculated by the database; EF Core reads them back after saving.
  • Sequences (HasSequence, UseHiLo) can pre-allocate ids and let EF Core batch inserts without waiting for identity values.

Who creates the value?

Your code Guid or natural key
The database Identity, default, computed
EF Core Sequential GUID, HiLo

Decide per property

1 / 2

Stand-in: how id generation changes what you know

This stand-in is not EF Core. It compares a database-generated integer (unknown until the insert) with a client-generated GUID (known at once).

C# Stand-in: database ids vs client ids

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.

Stand-in: composite keys in a dictionary

A composite key identifies a row by a combination of values. A C# tuple or record struct models it neatly.

C# Stand-in: a composite key

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

  • Reusing ids across entities with ValueGeneratedNever and forgetting to set them: every insert gets key 0.
  • Random Guid.NewGuid() as a clustered key on large SQL Server tables: works, but inserts scatter across the index. Prefer sequential or version-7 GUIDs.
  • Exposing int ids where guessing must not reveal data: add authorization checks regardless of key type; a GUID is not security.
  • Changing a key after saving: primary key values are immutable in EF Core. Create a new row instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. After SaveChanges, where does a database-generated int Id come from?

    EF Core reads the generated identity value and assigns it to the key property.
  2. 2. How do you define a composite primary key?

    Composite keys use HasKey with an anonymous type (or the class-level [PrimaryKey] attribute); [Key] on a single property cannot express them.
  3. 3. What is an advantage of a client-generated Guid key?

    You can create and reference the id in code before touching the database.
  4. 4. When is HasDefaultValue(true) on a bool tricky?

    false is default(bool), so EF Core cannot tell 'not set' from 'explicitly false' and the database default (true) is used.

Summary

  • Every entity needs a key; Id and <Class>Id are found by convention.
  • Integer keys are database-generated; GUIDs can be created in code (prefer sequential or version 7).
  • Composite keys use HasKey or [PrimaryKey]; alternate keys and unique indexes cover other identifiers.
  • Defaults, computed columns and row versions are other database-generated values.
  • A key never changes after the row exists.

Next: Value Converters and Owned Types