首页 > 解决方案 > 在 Entity Framework Core 中为多个表设置 SET IDENTITY_INSERT

问题描述

我想将表格设置IDENTITY_INSERTON. 我可以一次吃一张桌子。但是,当我采用代码优先方法时,如何实现不止一个。

我收到此错误:

System.Data.SqlClient.SqlException:IDENTITY_INSERT 已经为表“某些表”打开。无法对表 'ref.EmploymentType' 执行 SET 操作

测试.cs

using (var transaction = _referenceDataDbContext.Database.BeginTransaction())
{
    _referenceDataDbContext.EmploymentType.AddRangeAsync(
                new EmploymentTypeEntity
                {
                    EmploymentTypeID = 1,
                    EmploymentType = "EmploymentType1 ",
                    CategoryTypeID = 27,
                    SiteAddress = null,
                    CreatedBy = "UnitTest",
                    CreatedOn = DateTime.Now,
                    ModifiedBy = "UnitTest",
                    ModifiedOn = DateTime.Now,
                    RowVersion = new RowVersion(1),
                    EmploymentTypeGroups = new[]
                    {
                    new EmploymentTypeGroupEntity
                    {
                        EmploymentTypeGroupID = 11, GroupName = "GroupName", IsActive = true
                    }
                    }
                }
                }
            );

    _referenceDataDbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [ref].[EmploymentTypeGroup] ON");
    _referenceDataDbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [ref].[EmploymentType] ON");

    _referenceDataDbContext.SaveChanges();
}

标签: c#entity-framework-core

解决方案


删除如下行:

 EmploymentTypeGroups = new[]
 {
     new EmploymentTypeGroupEntity
     {
         EmploymentTypeGroupID = 71, GroupName="Some Data", IsActive = true
     }
 }

并移到_referenceDataDbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [ref].[EmploymentType] ON");线上方_referenceDataDbContext.EmploymentType.AddRangeAsync(

然后关闭 IDENTITY_INSERT。

然后重复整个过程以插入您的组记录。

这样,您一次只需要 IDENTITY_INSERT ON 一个表。


推荐阅读