I am trying to insert a new row to my table, using EF Core, SQL Server and C#, but I am having trouble getting EF Core to use the identity column properly.
Here's what I am doing:
I am creating a new object using the Entity Framework generated class (I've included the entity class definition at the end of my post)
EmployeePermissions employee_permission = new EmployeePermissions
{
FkEmployee = PkEmployee,
FkPermission = permission_key
};
Then I call db.EmployeePermissions.add(employee_permission)
, which works on all of my calls where an object comes from [FromBody] <Entity Class> <object_variable>
(albeit using other tables).
But here, when I instantiate the class myself, I get this error:
SqlException (0x80131904): Cannot insert explicit value for identity column in table 'Employee_Permissions' when IDENTITY_INSERT is set to OFF.
I don't understand why this is happening — I want it to auto increment the identity column. I used ObjectDumper
to see what is getting passed to .Add()
, which is as follows:
properties {
PkEmployeePermissions = 0 [System.Int32] // this is the identity column, of course
FkEmployee = 31 [System.Int32]
FkPermission = 6 [System.Int32]
FkEmployeeNavigation = <null>
FkPermissionNavigation = <null>
}
I have investigated the other calls which are working fine (the ones where [FromBody]
creates an object) and the identity column simply equals 0
in those calls too, so I don't understand what is different here.
Have I misconfigured something in the database? I have double checked in the column properties that the column PkEmployeePermissions
is indeed an identity column, so it should be auto incremented.
Here's the Entity class if it helps:
public partial class EmployeePermissions
{
public int PkEmployeePermissions { get; set; }
public int FkEmployee { get; set; }
public int FkPermission { get; set; }
public Employee FkEmployeeNavigation { get; set; }
public Permission FkPermissionNavigation { get; set; }
}