在Entity Framework Core中为多个表设置SET IDENTITY_INSERT

时间:2018-09-26 23:02:33

标签: c# entity-framework-core

我想将表IDENTITY_INSERT设置为ON。我一次只能坐一张桌子。但是当我在执行代码优先方法时,如何实现一个以上的目标。

我收到此错误:

  

System.Data.SqlClient.SqlException:表'Some Table'的IDENTITY_INSERT已经打开。无法对表'ref.EmploymentType'执行SET操作

Test.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();
}

1 个答案:

答案 0 :(得分:1)

删除这样的行:

const regex = new RegExp(this.state.searchValue);
const filteredCols = Object.keys(cols)
  .filter(key => key.match(regex))
  .reduce((filtered, key) => {
    filtered[key] = cols[key];
    return filtered;
  }, {});

filteredCols.map(function (col) {               
  return React.createElement(PropEntry, { name: col.Name, value: col.value });
});

并将 EmploymentTypeGroups = new[] { new EmploymentTypeGroupEntity { EmploymentTypeGroupID = 71, GroupName="Some Data", IsActive = true } } 移到_referenceDataDbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [ref].[EmploymentType] ON");行上方。

然后关闭IDENTITY_INSERT。

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

这样,您一次只需要为一张表打开IDENTITY_INSERT。