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.


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.





said:

sdfsdf

Posted On: November 27, 2020 11:44:16 AM

For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email AddressContact: [email protected]