我正在尝试关闭标识以插入我自己的值,我遵循的步骤
- 将标识列的属性
StoredGeneratedPattern
值更改为None
- 通过以 xml 格式打开,将 EDMX 文件中的属性
StoredGeneratedPattern
值更改为None
尝试使用下面的代码
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();
}
但是还是报错
Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF
我错过了什么吗?还有其他选择吗?
最佳答案
当您调用 TransactionScope.Complete 时,数据存储在数据库中,而不是当您调用 ClientInfoes.Add 或 Context.SaveChanges 时。所以您可以看到,当调用插入语句时,您已经关闭了 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");
}
更好的是,在事务之外对 IDENTITY_INSERT 进行所有更改,因为它的值是特定于 session 的(每个 session 只能为一个表打开它)。
关于c# - 无法将自定义值插入标识列 - Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12731163/