This is the query:
using (var db = new AppDbContext())
{
var item = new IdentityItem {Id = 418, Name = "Abrahadabra" };
db.IdentityItems.Add(item);
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Test.Items ON;");
db.SaveChanges();
}
When executed, the Id
of the inserted record, on a new table, is still 1.
NEW: When I use either the transaction, or TGlatzer's answer, I get the exception:
Explicit value must be specified for identity column in table 'Items' either when IDENTITY_INSERT is set to ON or when a replication user is inserting into a NOT FOR REPLICATION identity column.
"SET IDENTITY_INSERT Test.Items ON;"
followed by yourINSERT INTO...
and finally"SET IDENTITY_INSERT Test.Items OFF;"
(All in one query). Or, you can take a look at TransactionScope Class. – RogueryINSERT
query really defeats the purpose of an ORM. I much prefer the transaction option, but also prefer the built-in transaction, like in Aananda's answer. – Penmanship