C# 实体框架:IDENTITY_INSERT 问题 - “无法为表中的标识列插入显式值”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9622654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:13:59  来源:igfitidea点击:

Entity Framework: Issue with IDENTITY_INSERT - "Cannot insert explicit value for identity column in table"

c#entity-framework-4

提问by John Stone

I am using Entity Framework 4.0 with C#.NET. I am trying to create a "simple" migration tool to convert data from one table to another(the tables are NOT the same)

我在 C#.NET 中使用 Entity Framework 4.0。我正在尝试创建一个“简单”的迁移工具来将数据从一个表转换到另一个表(表不一样)

The database is a SQL Server 2005.

数据库是 SQL Server 2005。

I have a target DB structure similar to the following:

我有一个类似于以下的目标数据库结构:

MYID - int, primary key, identity specification (yes)
MYData - varchar(50)

In my migration program, I import the DB structure into the edmx. I then manually turn off the StoreGeneratedPattern.

在我的迁移程序中,我将数据库结构导入 edmx。然后我手动关闭 StoreGeneratedPattern。

In my migration program, I turn off the identity column as follows(I have verified it does indeed turn it off):

在我的迁移程序中,我按如下方式关闭了身份列(我已验证它确实将其关闭):

            using (newDB myDB = new newDB())
            {
                //turn off the identity column 
                myDB.ExecuteStoreCommand("SET IDENTITY_INSERT SR_Info ON");
            }

After the above code, I have the following code:

在上面的代码之后,我有以下代码:

            using (newDB myDB = new newDB())
            {
                DB_Record myNewRecord = new DB_Record();
                //{do a bunch of processing}
                myNewRecord.MYID = 50;
                myDB.AddToNewTable(myNewRecord);
                myDB.SaveChanges();
            }

When it gets to the myDB.SaveChanges(), it generates an exception: "Cannot insert explicit value for identity column in table".

当它到达 myDB.SaveChanges() 时,它会生成一个异常:“无法为表中的标识列插入显式值”。

I know the code works fine when I manually goto the SQL Server table and turn off the Identity Specification off.

我知道当我手动转到 SQL Server 表并关闭身份规范时代码工作正常。

My preference is to have the migration tool handle turning the Identity Specification on and off rather than have to manually do it on the database. This migration tool will be used on a sandbox database, a dev database, a QA database, and then a production database so fully automated would be nice.

我的偏好是让迁移工具处理打开和关闭身份规范,而不是必须在数据库上手动执行此操作。这个迁移工具将用于沙箱数据库、开发数据库、QA 数据库,然后是生产数据库,如此完全自动化会很好。

Any ideas for getting this to work right?

有什么想法可以让它正常工作吗?

I used the following steps:

我使用了以下步骤:

  1. Create database table with identity column.
  2. In Visual Studio, add a new EDMX.
  3. On EDMX, I select Update Model from Database (and select add the desired table)
  4. On EDMX, I click MYID and in the properties pane, I set StoreGeneratedProcedure to None.
  1. 创建带有标识列的数据库表。
  2. 在 Visual Studio 中,添加一个新的 EDMX。
  3. 在 EDMX 上,我选择从数据库更新模型(并选择添加所需的表)
  4. 在 EDMX 上,我单击 MYID,然后在属性窗格中将 StoreGeneratedProcedure 设置为 None。

At this point, when I add a new record with MYID set, the DB overwrites teh value of MYID with the Identity value.

此时,当我添加一条设置了 MYID 的新记录时,DB 会用 Identity 值覆盖 MYID 的值。

So far, no matter where I've added "myDB.ExecuteStoreCommand("SET IDENTITY_INSERT SR_Info ON");", it behalves the same way.

到目前为止,无论我在哪里添加了“myDB.ExecuteStoreCommand("SET IDENTITY_INSERT SR_Info ON");”,它的行为都是一样的。

I have tried adding a stored procedure and it also doesn't work.

我曾尝试添加存储过程,但它也不起作用。

I suspect that ultimately, the migration will not be fully automated.

我怀疑最终迁移不会完全自动化。

回答by Simon Whittemore

This looks promising Using IDENTITY_INSERT with EF4

这看起来很有希望使用 IDENTITY_INSERT 和 EF4

You basically need to make sure your data model knows about the changes you made to the database, as they are now no longer in sync with the underlying table.

您基本上需要确保您的数据模型知道您对数据库所做的更改,因为它们现在不再与基础表同步。

However, I don't recommend using EF as a heavy-weight data load tool. Prefer the SQL or ETL tooling.

但是,我不建议使用 EF 作为重量级的数据加载工具。更喜欢 SQL 或 ETL 工具。

回答by tetris

When column is identity, inserting record from Entity Framework will raise the following error:

当列是标识时,从实体框架插入记录将引发以下错误:

Cannot insert explicit value for identity column in table 'MY_ENTITY' when IDENTITY_INSERT is set to OFF. To avoid error set entity property StoreGeneratedPattern="Identity"

当 IDENTITY_INSERT 设置为 OFF 时,无法为表 'MY_ENTITY' 中的标识列插入显式值。为避免错误设置实体属性StoreGeneratedPattern="Identity"

<EntityType Name="MY_ENTITY">
    <Key>
        <PropertyRef Name="UserID" />
    </Key>
    <Property Name="RecordID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
</EntityType>

回答by Sid

protected override void OnModelCreating(DbModelBuilder modelBuilder)       
{
    modelBuilder.Entity<EntityClass>().HasKey(p => p.Id);

    modelBuilder.Entity<EntityClass>()
        .Property(c => c.Id)
        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

    base.OnModelCreating(modelBuilder);   
}