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.

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.

entity framework c asp.net core 3.1 Sql Error Technology published
Was this page helpful?
Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful.. Leave ErnesTech Feedback.Feedback

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

said:

sdfsdf

Your Session is Ending
Login to Continue


© 2021 - ErnesTech - Privacy