5

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?

4
  • Why do you want to start at 0 ?
    – Shyju
    Aug 24, 2018 at 22:24
  • @Shyju I have only 3 rows in particular table, and on the UI they need to have ID's 0,1,2 respectively. I know I can make another field of ID's and hardcore them for sake of UI, but I'm curious can I go without extra field.
    – gagro
    Aug 24, 2018 at 22:36
  • Post your code and what are you expecting, because simple answer to your question is Yes.
    – Pm Duda
    Aug 24, 2018 at 22:47
  • I would recommend not using identity at all on this table. Just an ordinary Id int primary key which you will populate with your explicit values.
    – Roger Wolf
    Aug 25, 2018 at 5:52

3 Answers 3

10

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);
}

8

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

2
  • 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?
    – gagro
    Aug 24, 2018 at 23:54
  • Create different sequence objects for each Entity. Aug 25, 2018 at 0:53
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.