I'm trying to insert a record into a table that has the ID auto generated. For this reason this is my code:
using (var context = new DbContext(GetConnection().Options))
{
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Customers ON;");
context.SaveChanges();
context.Customers.Add(customer);
context.SaveChanges();
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Customers OFF;");
}
But the exception is always the same:
Cannot insert explicit value for identity column in table 'Customers' when IDENTITY_INSERT is set to OFF.
I also tried to execute the command SET IDENTITY_INSERT dbo.Customers ON
manually in SQL Server Management Studio and after execute the code above but the same exception is thrown.
Why?
IDENTITY
column is that you don't have to worry about providing proper values - SQL Server will handle that for you ..... – marc_s Nov 13 at 17:50