Setting SET IDENTITY_INSERT for multiple tables in Entity Framework Core

独自空忆成欢 提交于 2019-12-11 08:05:47

问题


I want to set tables IDENTITY_INSERT to 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'. Cannot perform SET operation for table 'ref.EmploymentType'

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:


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"); to above the _referenceDataDbContext.EmploymentType.AddRangeAsync( line.

then turn IDENTITY_INSERT OFF.

Then repeat the whole thing to insert your group records.

This way you only need IDENTITY_INSERT ON for one table at a time.



来源:https://stackoverflow.com/questions/52527144/setting-set-identity-insert-for-multiple-tables-in-entity-framework-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!