Setting SET IDENTITY_INSERT for multiple tables in Entity Framework Core

c# entity-framework-core

Question

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
2
9/27/2018 4:29:49 AM

Popular Answer

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.

1
9/26/2018 11:48:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow