How to turn on identity-insert in .net core

后端 未结 9 1310
日久生厌
日久生厌 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:08

    Had to deal with the same issue and this seems to be a clean solution.

    Credit to >> https://github.com/dotnet/efcore/issues/11586

    I have made some changes so it now works with .Net Core 3.1 + (Tested in .Net 5) and also added this Method SaveChangesWithIdentityInsert

        public static class IdentityHelpers
    {
        public static Task EnableIdentityInsert(this DbContext context) => SetIdentityInsert(context, enable: true);
        public static Task DisableIdentityInsert(this DbContext context) => SetIdentityInsert(context, enable: false);
    
        private static Task SetIdentityInsert(DbContext context, bool enable)
        {
            var entityType = context.Model.FindEntityType(typeof(T));
            var value = enable ? "ON" : "OFF";
            return context.Database.ExecuteSqlRawAsync(
                $"SET IDENTITY_INSERT {entityType.GetSchema()}.{entityType.GetTableName()} {value}");
        }
    
        public static void SaveChangesWithIdentityInsert(this DbContext context)
        {
            using var transaction = context.Database.BeginTransaction();
            context.EnableIdentityInsert();
            context.SaveChanges();
            context.DisableIdentityInsert();
            transaction.Commit();
        }
    
    }
    

    Usage

            var data = new MyType{SomeProp= DateTime.Now, Id = 1};
                context.MyType.Add(data);
            context.SaveChangesWithIdentityInsert();
    

提交回复
热议问题