问题
I am trying to switch the identity off to insert my own value, steps I followed
- changed the property
StoredGeneratedPattern
value toNone
for the identity column - changed the property
StoredGeneratedPattern
value toNone
in EDMX file by opening in xml format
Tried using the below code
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
int k = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client ON");
Context.ClientInfoes.Add(testclient);
result = Context.SaveChanges();
int j = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client OFF");
scope.Complete();
}
but I am still receiving the error
Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF
Am I missing something? Are there any other options?
回答1:
The data is stored in the database when you call TransactionScope.Complete, not when you call ClientInfoes.Add or Context.SaveChanges. So you can see that when the insert statement is called you have already switched IDENTITY INSERT back off.
Simply rearrange things...
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
int k = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client ON");
Context.ClientInfoes.Add(testclient);
result = Context.SaveChanges();
scope.Complete();
int j = Context.ExecuteStoreCommand("SET IDENTITY_INSERT dbo.client OFF");
}
Better yet, do all your changes to IDENTITY_INSERT outside of the transaction since it's value is session specific (you can only have it switched on for one table per session).
回答2:
See the similar question here.
Eranga explains:
ExecuteSqlCommand
will open the connection, execute the sql and then close it. So your next command will execute using a different connection.
The ExecuteSqlCommand method is similar to the ExecuteStoreCommand.
Daniel Liuzzi explains:
... the trick is packing everything into a single command...
So for example,
string sqlStatement = "SET IDENTITY_INSERT clientInfo ON;" +
string.Format("INSERT clientInfo (ClientInfoId, Column1, Column2) VALUES ({0}, {1}, {2}, '{3}');", testClient.ClientInfoId, testClient.Column1, testclient.Column2) +
"SET IDENTITY_INSERT clientInfo OFF";
context.ExecuteStoreCommand(sqlStatement);
来源:https://stackoverflow.com/questions/12731163/cannot-insert-custom-value-into-identity-column-entity-framework