EF 7 Identity Insert Issue

entity-framework entity-framework-core

Question

I have to be able to set the primary key of the entities I am trying to add in my list "final_zones". I have a controller constructor as follows:

    public UtilController(CFETSContext context)
    {
        _context = context; 
    }
     ......Then in a web api method.........
        using (var transaction = _context.Database.BeginTransaction())
        {
            _context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [CFETSWeb].[dbo].[Zone] ON");             

            _context.SaveChanges();
            transaction.Commit();
        }


       using (var transaction = _context.Database.BeginTransaction())
        {             
            _context.Zones.AddRange(final_zones);
            _context.SaveChanges(); //ERROR HERE
            transaction.Commit();
        }

No matter what I do, I cannot seem to get IDENTITY_INSERT to turn on. I get the following error:

{"Cannot insert explicit value for identity column in table 'Zone' when IDENTITY_INSERT is set to OFF."}

I just can't seem to get it to turn off. I can add entities to my DB in the controller, so I know everything else is working. I have tried doing this without a transaction as well with the same result.

 _context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [CFETSWeb].[dbo].[Zone] ON"); 
_context.Zones.AddRange(final_zones);
        _context.SaveChanges();

Any ideas? I am at a loss for what to try next. Thanks.

1
2
8/18/2016 5:11:30 PM

Popular Answer

I solved it with the following:

       using (var dbContextTransaction = _context.Database.BeginTransaction())
        {
            try
            {
                _context.Database.ExecuteSqlCommand(@"SET IDENTITY_INSERT [CFETSWeb].[dbo].[Zone] ON");
                _context.Zones.AddRange(final_zones);
                _context.SaveChanges();          

                dbContextTransaction.Commit();
            }
            catch (Exception e)
            {
                dbContextTransaction.Rollback();
            }
        }

NOTE: You HAVE to do this per table. IDENTITY_INSERT can only be set for 1 table at a time it seems, so you can do it this way or toggle it to OFF in the same transaction.

Also, IDENTITY_INSERT has to be in a transaction, as it only stays on for the duration of a transaction.

4
8/18/2016 6:40:58 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