SqlExeption: Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF

Question: How do you resolve the Entity Framework Error that says: SqlExeption: Cannot insert explicit value for identity column in table "Table Name" when IDENTITY_INSERT is set to OFF.


Please Login to see the rest of the answer

Answer:

-Make sure that the Database Table has a primary key defined and that the primary key autoincrement value on insert.

- Make sure that your Id property in the Model Class is not a string, it should be an int.

- Add  [DatabaseGenerated(DatabaseGeneratedOption.Identity)] on top of the Id property in your Model Class.

- [Do not Adivise] If you need to, make sure you set IDENTITY_INSET to ON when creating a store procedure or using LINQ in C# code. But I wouldn't advise this as it makes the Entity Framework think that the code is responsible for generating Row Id's. The case of the matter should be that the Database should generate ID's and not the Application code unless otherwise Sequence HiLo id insertion, this is where application generates a bunch of ID's then inserts into the database table because of certain requirement in the Business logic. This scenario is not common unless required.


Write an Article
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

said:

sdfsdf


© 2022 - ErnesTech - Privacy