[英]Setting SET IDENTITY_INSERT for multiple tables in Entity Framework Core
I want to set tables IDENTITY_INSERT
to ON
.我想将表
IDENTITY_INSERT
设置为ON
。 I can for one table at a time.我可以一次吃一张桌子。 But how can I achieve for more than one as I am doing code-first approach.
但是当我在做代码优先的方法时,我怎么能做到不止一个。
I'm getting this error:我收到此错误:
System.Data.SqlClient.SqlException : IDENTITY_INSERT is already ON for table 'Some Table'.
System.Data.SqlClient.SqlException : IDENTITY_INSERT 对于表“Some Table”已经打开。 Cannot perform SET operation for table 'ref.EmploymentType'
无法对表“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();
}
Remove the lines such as this:删除这样的行:
EmploymentTypeGroups = new[]
{
new EmploymentTypeGroupEntity
{
EmploymentTypeGroupID = 71, GroupName="Some Data", IsActive = true
}
}
and move _referenceDataDbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [ref].[EmploymentType] ON");
并移动
_referenceDataDbContext.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [ref].[EmploymentType] ON");
to above the _referenceDataDbContext.EmploymentType.AddRangeAsync(
line.到
_referenceDataDbContext.EmploymentType.AddRangeAsync(
行上方。
then turn IDENTITY_INSERT OFF.然后关闭 IDENTITY_INSERT。
Then repeat the whole thing to insert your group records.然后重复整个过程以插入您的组记录。
This way you only need IDENTITY_INSERT ON for one table at a time.这样您一次只需要对一张表进行 IDENTITY_INSERT ON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.