Charindri Perera
Charindri Perera

Reputation: 111

How to set starting value for an Identity primary key in Entity Framework code first?

In my project I am creating the Appointments table using Entity Framework code first. When I set my integer primary key, AppointmentNo as [Key] and [Required], it creates the table with initial primary key starting with 1.

I want the appointment numbers to start at 1000. My database is SQL Server. Please help me. Thank you in advance.

[DataContract]
public class Appointment
{
    [DataMember]
    [Key]
    [Required]
    public int AppointmentNo { get; set; }

    [DataMember]
    [Required]
    public string DoctorUN { get; set; }

    [DataMember]
    [Required]
    public string PatientUN { get; set; }
}

Upvotes: 8

Views: 11865

Answers (4)

Jame
Jame

Reputation: 241

In entity framework you can do this:

builder.Entity<EntityName>(b =>
        {
            b.ToTable("TabelName");
            b.Property(x => x.ColumnName).ValueGeneratedOnAdd().UseIdentityColumn(1000,1);
        });

Upvotes: 8

TheNightOwl
TheNightOwl

Reputation: 668

EF Core 3.1 You can open your migration script and edit it before updating database. EF creates this line for the identity column: .Annotation("SqlServer:Identity", "1, 1"),

you can update it to anything you want:

.Annotation("SqlServer:Identity", "Your Starting Value, Your Increment Value"),

Example: If I want OrderId column on tblOrder to start from 1000 and increment by 1:

migrationBuilder.CreateTable(
    name: "tblOrder",
    schema: "dbo",
    columns: table => new
    {
        OrderID = table.Column<int>(nullable: false)
            .Annotation("SqlServer:Identity", "1000, 1"),        
        CDate = table.Column<DateTime>(nullable: false, defaultValueSql: "getdate()")
    },
.
.
.

Upvotes: 6

vborutenko
vborutenko

Reputation: 4443

It's not possible using ef annotations,but you can execute sql in migration UP method

Sql("DBCC CHECKIDENT ('Appointment', RESEED, 1000)");

Upvotes: 6

user1443098
user1443098

Reputation: 7625

As long as the type of the primary key property is numeric or GUID, Code First will, by convention, automatically configure the key as an identity column.

from:EF and identity columns

Upvotes: -3

Related Questions