【问题标题】:Entity Framework IDENTITY_INSERT ON doesn't work实体框架 IDENTITY_INSERT ON 不起作用
【发布时间】:2013-04-19 04:13:02
【问题描述】:

我有这段代码应该插入带有身份插入的记录

using (MCT_DB_ArchiveEntities ent = new MCT_DB_ArchiveEntities())
{
  ent.ExecuteStoreCommand("SET IDENTITY_INSERT [clicks] ON");
  ent.clicks.Attach(ck);
  ent.clicks.Context.ObjectStateManager.ChangeObjectState(ck, System.Data.EntityState.Added);
  ent.SaveChanges();
}

我收到此错误。

当 IDENTITY_INSERT 设置为 OFF 时,无法为表“clicks”中的标识列插入显式值。

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    它不应该工作。仅当身份插入在与真实插入相同的连接上打开时才有效。在您的情况下,可以使用两种不同的连接。要使其工作,您必须维护自己的数据库连接并将其传递给 ObjectContext 的构造函数。

    【讨论】:

    • 谢谢!我能够使用 TransactionScope 让它工作
    【解决方案2】:

    根据之前的Question,您需要开始您的上下文事务。保存更改后,您还必须重新声明 Identity Insert 列,最后您必须提交事务。

    using (MCT_DB_ArchiveEntities ent = new MCT_DB_ArchiveEntities())
    using (var transaction = ent.Database.BeginTransaction())
    {
        var item = new User {Id = 418, Name = "Abrahadabra" };
        ent.IdentityItems.Add(item);
        ent.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Test.Items ON;");
        ent.SaveChanges();
        ent.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");
        transaction.Commit();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-27
      • 1970-01-01
      • 2011-06-27
      • 2016-04-16
      • 2012-08-13
      • 2011-04-28
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多