5

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; }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

4 Answers4

6

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

Sql("DBCC CHECKIDENT ('Appointment', RESEED, 1000)");
vborutenko
  • 4,323
  • 5
  • 28
  • 48
  • 1
    I created the table from the SQL Server Management Studio and used your query there before I executed my code, that got the job done. Thanks – Charindri Perera Sep 17 '18 at 20:11
5

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()")
    },
.
.
.
TheNightOwl
  • 528
  • 5
  • 6
5

In entity framework you can do this:

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

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

user1443098
  • 6,487
  • 5
  • 38
  • 67