Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFrameworkCore Key column auto increment from specific value

A simple class with an auto-incremented Key column

public class SomeClass
{
    [Key]
    public long SomeClassId { get; set;}
}

Normally the SomeClassId will start and auto-increment from 1. Is there anyway to force the ID to start from a specific number, say 10001?

It was suggested here to execute the CHECKIDENT command through Sql(). But I wonder if there are other ways to go about this?

Thanks!

like image 232
VT Chiew Avatar asked Nov 28 '25 02:11

VT Chiew


1 Answers

Yes, You can use the Fluent API .sample code

class MyContext : DbContext
{
    public DbSet<SomeClass> sample{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasSequence<int>("sampleNumber", schema: "shared")
            .StartsAt(10001)
            .IncrementsBy(1);  
        modelBuilder.Entity<SomeClass>()
        .Property(o => o.SomeClassId)
        .HasDefaultValueSql("NEXT VALUE FOR shared.sampleNumber");
    }
    }
like image 110
SUNIL DHAPPADHULE Avatar answered Nov 29 '25 17:11

SUNIL DHAPPADHULE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!