How to turn on identity-insert in .net core

后端 未结 9 1302
日久生厌
日久生厌 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 07:49

    Another way is to use ExecuteSqlRaw. Unlike ExecuteSqlInterpolated, you do not have to convert your passed string to a formattable string type.

    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.ExecuteSqlRaw("SET IDENTITY_INSERT MyDB.Users ON");
        db.SaveChanges();
        db.Database.ExecuteSqlRaw("SET IDENTITY_INSERT MyDB.Users OFF");
        transaction.Commit();
    

    ` }

提交回复
热议问题