Abdul Asim
Abdul Asim

Reputation: 23

How to modify Random().Next() to Autoincrementing

I am doing an ASP.NetCore MVC Project.

Following is the code I am using to insert the primary key of the table 'ImageFile'.
(It has attributes like: Id, UserID, ImageName, Size, URl etc. UserId is a foreign key).

ImageFile imageFile = new ImageFile();
imageFile.Id = new Random().Next();

This just inserts a random number into the Id field of the table.
Ex:

ID UserId ImageName
1513570791 2 image1.png
1714580687 2 image2.png
5909420604 2 image3.png

How can I modify the above code snippet to insert an auto-incrementing value to the table ?
Ex:

ID UserId ImageName
1 2 image1.png
2 2 image2.png
3 2 image3.png

Thank you.

Upvotes: 2

Views: 62

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063774

From comments

"I am using a microsoft sql database"

Then: define the column (presumably Id) as IDENTITY(1,1), for example Id int not null IDENTITY(1,1) - and you're done. Now the database assigns the value during INSERT - starting from 1 and incrementing 1 each time, and you cannot UPDATE it etc. If you are using an ORM such as EF, you will need to tell it that the column is database owned; there's usually an attribute for that (so it doesn't try to push that value into the database), for example [DatabaseGenerated(DatabaseGeneratedOption.Identity)].

Upvotes: 7

Related Questions