Course contentsShow
← C#
Lesson 1128 of 1,90810. Entity Framework Core ModelingFree lesson

Configuring Identity Columns

Manage custom identity seed and increment settings for unique key generation.

In this lesson, you will learn how to precisely control the starting point and growth pattern of your database identity columns using Entity Framework Core.

By default, when you mark a property as an identity column (often via ValueGeneratedOnAdd), SQL Server starts counting at 1 and increments by 1 for every new record. However, you might need to adjust these settings—for example, if you are migrating legacy data or if your business requirements demand that IDs start at 10,000 and increment by 5 to avoid collisions or to mask the total number of records.

You configure these settings within your DbContext using the Fluent API inside the OnModelCreating method. EF Core provides the HasIdentityColumn method, which accepts optional parameters for seed and increment.

Implementation Example

To customize your primary key generation, target the entity's property as shown below:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
        .Property(o => o.OrderId)
        .UseIdentityColumn(seed: 1000, increment: 10);
}

In this scenario, the first record inserted into the Orders table will receive an OrderId of 1000. The next record will receive 1010, the following 1020, and so on.

When to use this

This configuration is particularly useful during data migrations. If you are importing records from an external system that already uses a specific range of IDs, setting a custom seed ensures that your new entity inserts don't clash with existing primary keys. It is also a handy way to prevent "guessability" in public-facing URLs by using a larger increment, though keep in mind this is not a substitute for proper security measures.

Always remember that these settings are provider-specific. While UseIdentityColumn works seamlessly with SQL Server, other databases might require different approaches (like HasSequence or HasDefaultValueSql) to achieve the same result.

Key Takeaway: You can manage your unique key generation strategy by using UseIdentityColumn(seed, increment) in the Fluent API to gain granular control over how your database assigns new identifiers.