简体   繁体   中英

Setting SET IDENTITY_INSERT for multiple tables in Entity Framework Core

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM