【问题标题】:Cannot Insert custom value into identity column - Entity Framework无法将自定义值插入标识列 - 实体框架
【发布时间】:2012-09-25 17:15:39
【问题描述】:

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

  1. 将标识列的属性StoredGeneratedPattern 值更改为None
  2. 将EDMX文件中的StoredGeneratedPattern属性值更改为None,以xml格式打开

尝试使用以下代码

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 设置为关闭

我错过了什么吗?还有其他选择吗?

【问题讨论】:

  • 您的上下文是 ClientInfoes,但您的 SQL 是 dbo.client。 ClientInfoes 是否映射到客户端?还是客户信息表?
  • clientinfoes映射到client,client是sql中的表。没有身份,插入工作正常,但我的要求是传递自定义客户端 ID。

标签: c# entity-framework entity-framework-4 entity-framework-4.1 identity


【解决方案1】:

当您调用 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 进行所有更改,因为它的值是特定于会话的(您只能为每个会话打开一个表)。

【讨论】:

    【解决方案2】:

    查看类似问题here

    埃兰加解释道:

    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);
    

    【讨论】:

    • 您希望删除 string.Format 并正确参数化您的命令;否则您将面临 SQL 注入攻击。
    猜你喜欢
    • 2017-03-05
    • 1970-01-01
    • 2015-10-18
    • 2020-11-22
    • 1970-01-01
    • 2016-07-05
    • 2012-06-25
    • 1970-01-01
    相关资源
    最近更新 更多