I\'m using code first with entity framework. I have been getting the error below and can\'t figure out how to fix it:
\"Cannot insert explicit value for identity col
You have to first turn it ON, then do your insert and then turn it OFF
Sql("SET IDENTITY_INSERT Genres ON");
Sql("INSERT INTO Genres (Id, Name) VALUES (1, 'Action')");
Sql("INSERT INTO Genres (Id, Name) VALUES (2, 'Thriller')");
Sql("INSERT INTO Genres (Id, Name) VALUES (3, 'Family')");
Sql("INSERT INTO Genres (Id, Name) VALUES (4, 'Romance')");
Sql("INSERT INTO Genres (Id, Name) VALUES (5, 'Comedy')");
Sql("SET IDENTITY_INSERT Genres OFF");
But, the point of having an identity column is that we don't choose what values the identity holds (read up on surrogate keys). In that case, you just remove the ID column from your insert
Sql("INSERT INTO Genres (Name) VALUES ('Action')");
Sql("INSERT INTO Genres (Name) VALUES ('Thriller')");
Sql("INSERT INTO Genres (Name) VALUES ('Family')");
Sql("INSERT INTO Genres (Name) VALUES ('Romance')");
Sql("INSERT INTO Genres (Name) VALUES ('Comedy')");
You could easily avoid this error by not specifying the Id
, when you insert a record to the Genres table. As it seems Id
is an IDENTITY COLUMN. Hence you don't have to specify a value when you insert there a record. The database would generate always the correct Id
value based on the IDENTITY you have defined. Usually we have Columns of type INT and IDENTITY(1,1). That means that the first row that would be inserted would have as an Id
the value of 1. The second row the value of 2 and so on and so forth.
For further info please have a look here.
Regarding the error message you get about to IDENTITY_INSERT...
, the command SET IDENTITY_INSERT can be used when we want to insert one (or more) explicit value(s) to a column with an IDENTITY. A detailed explanation on how to use this command you can find here.