How to turn on identity-insert in .net core

后端 未结 9 1297
日久生厌
日久生厌 2020-12-15 07:12

I made a few tables in EF and entered in some seed data where I give value to a few columns with a primary key. When I run the application I am getting the error message: <

9条回答
  •  天涯浪人
    2020-12-15 08:07

    @Steve Nyholm answer is OK, But in .Net core 3 ExecuteSqlCommand is Obsolete, ExecuteSqlInterpolated replacement of ExecuteSqlCommand:

    using (var db = new AppDbContext())
    using (var transaction = db.Database.BeginTransaction())
    {
        var user = new User {Id = 123, Name = "Joe"};
        db.Users.Add(user);
        db.Database.ExecuteSqlInterpolated($"SET IDENTITY_INSERT MyDB.Users ON;");
        db.SaveChanges();
        db.Database.ExecuteSqlInterpolated($"SET IDENTITY_INSERT MyDB.Users OFF");
        transaction.Commit();
    }
    

提交回复
热议问题