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?
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
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.