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?
3 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);
}
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://learn.microsoft.com/en-us/ef/core/modeling/relational/sequences
-
if I'm right, according to this all of my DbSets inside Context class will start with 0? What if I want just one DbSet (table) to start with 0?– gagroAug 24, 2018 at 23:54
-
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.
identity
at all on this table. Just an ordinaryId int primary key
which you will populate with your explicit values.