IDENTITY_INSERT during seeding with EntityFramework 6 Code-First

后端 未结 9 714
遥遥无期
遥遥无期 2020-12-05 10:19

I have an entity that has an Auto-identity (int) column. As part of the data-seed I want to use specific identifier values for the \"standard data\" in my syste

9条回答
  •  既然无缘
    2020-12-05 11:06

    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 (var transaction = context.Database.BeginTransaction())
    {
        var item = new ReferenceThing{Id = 418, Name = "Abrahadabra" };
        context.IdentityItems.Add(item);
        context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Test.Items ON;");
        context.SaveChanges();
        context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT [dbo].[User] OFF");
        transaction.Commit();
    }
    

提交回复
热议问题