April 17, 2022 / by Zsolt Soczó

EF Core HiLo sequence increment – it might not be what you have expected

It is not obvious, but when you use HiLo key generation strategy for EF Core, the increment of the underlying sequence should be 10 instead of the standard 1.

NHibernate explicitly increment the sequence by the specified value when it gets the next Hi number. However, EF Core simply calls NEXT VALUE FOR SequenceName, because it expects the increment to be equal of the size of the Hi part. This is understandable, but it was unexpected to me.

If you make the sequence definition part of the metadata, then you can specify a different increment and so a Hi range:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasSequence<int>("TickerSequence", schema: "dbo")
        .StartsAt(1000)
        .IncrementsBy(50);
}

If you use migration to create the sequence, the increment will be 50 instead of 1.

When EF HiLo strategy calls NEXT VALUE FOR TickerSequence, SQL Server will increment the sequence by 50, and EF Core persistence logic will use this knowledge when assign a new Hi part for the next primary key.