无法将自定义值插入标识列 – entity framework
我试图切换身份以插入我自己的值,我遵循的步骤
- 将标识列的属性
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(); }
但我仍然收到错误
当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"); }
更好的是,在事务之外对IDENTITY_INSERT进行所有更改,因为它的值是特定于会话的(每个会话只能为一个表启用它)。
在这里看到类似的问题。
Eranga解释说:
ExecuteSqlCommand
将打开连接,执行sql然后关闭它。 所以你的下一个命令将使用不同的连接执行。
ExecuteSqlCommand方法类似于ExecuteStoreCommand。
Daniel Liuzzi解释说:
……诀窍是将所有东西都包装成一个命令……
例如,
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);