Entity Framework IDENTITY_INSERT ON doesn't work

后端 未结 2 776
太阳男子
太阳男子 2021-01-19 08:46

I have this code that is supposed to insert the record with identity insert on

using (MCT_DB_ArchiveEntities ent = new MCT_DB_ArchiveEntities())
{
  ent.Exec         


        
相关标签:
2条回答
  • 2021-01-19 08:57

    It is not supposed to work. It works only if the identity insert is turned on on the same connection as the real insert. In your case two different connections can be used. To make it work you have to maintain your own DB connection and pass it to ObjectContext's constructor.

    0 讨论(0)
  • 2021-01-19 09:07

    According to this previous Question you need to begin a transaction of your context. After saving the change you have to restate the Identity Insert column too and finally you must have to commit the transaction.

    using (MCT_DB_ArchiveEntities ent = new MCT_DB_ArchiveEntities())
    using (var transaction = ent.Database.BeginTransaction())
    {
        var item = new User {Id = 418, Name = "Abrahadabra" };
        ent.IdentityItems.Add(item);
        ent.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Test.Items ON;");
        ent.SaveChanges();
        ent.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");
        transaction.Commit();
    }
    
    0 讨论(0)
提交回复
热议问题