Vam*_*msi 5 c# identity entity-framework entity-framework-4 entity-framework-4.1
我试图关闭身份以插入我自己的值,我遵循的步骤
StoredGeneratedPattern值更改None为标识列 StoredGeneratedPattern值更改为NoneEDMX文件尝试使用以下代码
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();
}
Run Code Online (Sandbox Code Playgroud)
但我仍然收到错误
当IDENTITY_INSERT设置为OFF时,无法在表中插入标识列的显式值
我错过了什么吗?还有其他选择吗?
当您调用 TransactionScope.Complete 时,而不是当您调用 ClientInfoes.Add 或 Context.SaveChanges 时,数据将存储在数据库中。因此您可以看到,当调用 insert 语句时,您已经关闭了 IDENTITY INSERT。
简单地重新安排一下事情...
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");
}
Run Code Online (Sandbox Code Playgroud)
更好的是,在事务外部对 IDENTITY_INSERT 进行所有更改,因为它的值是特定于会话的(每个会话只能为一个表打开它)。
| 归档时间: |
|
| 查看次数: |
1858 次 |
| 最近记录: |