无法将自定义值插入标识列-Entity Framework [英] Cannot Insert custom value into identity column - Entity Framework
问题描述
我正在尝试关闭身份以插入自己的值,这是我遵循的步骤
I am trying to switch the identity off to insert my own value, steps I followed
- 将标识列的属性
StoredGeneratedPattern
值更改为None
- 通过以xml格式打开,将EDMX文件中的属性
StoredGeneratedPattern
值更改为None
- changed the property
StoredGeneratedPattern
value toNone
for the identity column - changed the property
StoredGeneratedPattern
value toNone
in EDMX file by opening in xml format
尝试使用以下代码
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();
}
但是我仍然收到错误
在以下情况下无法为表中的标识列插入显式值 IDENTITY_INSERT设置为OFF
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?
推荐答案
请参阅类似的问题.
See the similar question here.
Eranga解释:
ExecuteSqlCommand
将打开连接,执行sql,然后 关闭它.因此,您的下一条命令将使用其他命令执行 连接.
ExecuteSqlCommand
will open the connection, execute the sql and then close it. So your next command will execute using a different connection.
ExecuteSqlCommand方法类似于ExecuteStoreCommand.
The ExecuteSqlCommand method is similar to the ExecuteStoreCommand.
Daniel Liuzzi解释:
Daniel Liuzzi explains:
...诀窍是将所有内容打包到一个命令中...
... the trick is packing everything into a single command...
例如,
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);
这篇关于无法将自定义值插入标识列-Entity Framework的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!