Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto increment PK starting from zero - EF Core code-first

I'm using ASP.NET Core and EF Core with code-first approach. Database is SQL Server. Is it possible to increment Id primary key starting at 0?

like image 485
gagro Avatar asked Aug 24 '18 22:08

gagro


People also ask

Can auto increment be a primary key?

Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table. Often this is the primary key field that we would like to be created automatically every time a new record is inserted.

How do I use code first in Entity Framework Core?

Code-First is mainly useful in Domain Driven Design. In the Code-First approach, you focus on the domain of your application and start creating classes for your domain entity rather than design your database first and then create the classes which match your database design.

What does the auto increment sequence begin at by default?

Explanation: The AUTO_INCREMENT column attribute provides unique numbers for column identification. AUTO_INCREMENT sequences normally begin at 1 and increase monotonically like 1, 2, 3, and so on.

Can Unique Key be set for auto increment?

A unique key does not supports auto increment value. We cannot change or delete values stored in primary keys. We can change unique key values.


2 Answers

With EF Core 3.x you can use UseIdentityColumn:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // ...

    modelBuilder.Entity<Blog>()
        .Property(x => x.Id)
        .UseIdentityColumn(seed: 0, increment: 1);
}

like image 116
Peyman M. Avatar answered Oct 06 '22 02:10

Peyman M.


Is it posible to increment Id primary key starting at 0?

Yes. EF Core supports Sequences, which you can start wherever you want.

EG:

class MyContext : DbContext
{
    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasSequence<int>("Order_seq", schema: "dbo")
            .StartsAt(0)
            .IncrementsBy(1);

        modelBuilder.Entity<Order>()
            .Property(o => o.OrderNo)
            .HasDefaultValueSql("NEXT VALUE FOR dbo.Order_seq");
    }
}

public class Order
{
    public int OrderId { get; set; }
    public int OrderNo { get; set; }
    public string Url { get; set; }
}

https://docs.microsoft.com/en-us/ef/core/modeling/relational/sequences

like image 23
David Browne - Microsoft Avatar answered Oct 06 '22 03:10

David Browne - Microsoft