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

asp.net-core c# entity-framework-core sql-server

Question

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?

1
2
8/25/2018 6:52:28 AM

Accepted Answer

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

6
8/24/2018 11:03:05 PM

Popular Answer

If you are creating the table using T-SQL Script?

You can create an IDENTITY (Property) (Transact-SQL) column as follows:

Syntax:

IDENTITY [ (seed , increment ) ]

SQL:

CREATE TABLE (
  ID_column INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
  ...
);

The IDENTITY property will auto-increment the column up from number 1. (Note that the data type of the column should be an integer.) If you want to add this to an existing column, use an ALTER TABLE command.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow