How do I generate a primary key that is not random?

c# data-annotations entity-framework-core

Question

I want to be able to set the value of my primary key to an auto increment number. At the moment it generates a random key such as 13917c50-6b8c-4405-82ce...

I want to be able to tell the system "Hey, I want request number to start at 1 (or 1000 or whatever) and auto increment every time a record is saved."

public class Request
{
    [Key]
    public string request_no { get; set; }

I expect, as a record is saved, for a request number of my choosing to be auto generated.

1
-1
2/9/2019 8:48:17 PM

Accepted Answer

Use DatabaseGenerated attribute:

public class Request
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int request_no { get; set; }
}

Also if you want to create seed for request_no then you should use custom database initializer and execute DBCC CHECKIDENT query:

DBCC CHECKIDENT ('Request', RESEED, 1000)
0
2/9/2019 8:53:14 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow