"Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF" with composite key

The problem is on ID. If you set a field as IDENTITY you can't normally assign it a value - the IDENTITY property marks it as allowing the database to automatically assign an incrementing value to the column.

To solve this problem, either remove the automatic IDENTITY property from ID (if you want to auto-increment it, you can always do this in your handling code - get the highest value in the field, add one to it and then assign that value) or go to the DB and set IDENTITY _INSERT on the table, which temporarily allows you to assign values to IDENTITY fields.

SET IDENTITY_INSERT [yourTableName] ON

--go back and run your C# code>

SET IDENTITY_INSERT [yourTableName] OFF

After sleeping, I found this, for Visual Studio c# code : [DatabaseGenerated(DatabaseGeneratedOption.Identity)]. This (in my words), defined for each of my ID fields, tells Visual Studio that the field is an Identity and to "leave it alone" when sending values to the database. When Company_ID occurs first, and has a value, telling Visual Studio that there is an Identity field elsewhere allows the _db.Project.Add(newProject); and then _db.SaveChanges(); to function as required. This part of the answer is for the Visual Studio side of things. I understand the SQL requirements of IDENTIY_INSERT so thanks to @matt-thrower, @steve-pettifer and the others who contributed.


What worked for me was a simple EDMX update. As I had set Identity Off before and then changed it to auto. But did not update the Edmx . After updating it worked fine.