EF 7 Identity Insert Issue

后端 未结 2 1889
你的背包
你的背包 2020-12-11 10:37

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:

    publi         


        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 11:02

    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.

提交回复
热议问题