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?
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.
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.
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.
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.
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://docs.microsoft.com/en-us/ef/core/modeling/relational/sequences
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With