c# - 在 Entity Framework Core 中为多个表设置 SET IDENTITY_INSERT
问题描述
我想将表格设置IDENTITY_INSERT
为ON
. 我可以一次吃一张桌子。但是,当我采用代码优先方法时,如何实现不止一个。
我收到此错误:
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();
}
解决方案
删除如下行:
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 一个表。
推荐阅读
- python-3.x - Python GetActiveObject - Run Photoshop Action
- python - Error in finding linkeding profile using python linkedin-scraper 2.6.0
- bash - Redirect all messages to log file from inside script except some print command output on console as well as screen
- php - ACF 灵活内容 - 循环两个布局(解析错误?)
- javascript - async/await 语法有时似乎不起作用
- python - 套接字无法接收字节
- java - Shadow jar 缺少常见的 java 类
- javascript - 如何使用 vanilla JS 在滚动时平滑滚动到 div?
- robotframework - 使用 JiraRobot 库但无法在 Robot Framework 中连接 Jira
- cython - 是否可以在 Cython 中声明和定义位字段?