无法将自定义值插入标识列-Entity Framework [英] Cannot Insert custom value into identity column - Entity Framework

查看:112
本文介绍了无法将自定义值插入标识列-Entity Framework的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试关闭身份以插入自己的值,这是我遵循的步骤

I am trying to switch the identity off to insert my own value, steps I followed

  1. 将标识列的属性StoredGeneratedPattern值更改为None
  2. 通过以xml格式打开,将EDMX文件中的属性StoredGeneratedPattern值更改为None
  1. changed the property StoredGeneratedPattern value to None for the identity column
  2. changed the property StoredGeneratedPattern value to None 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆