IDENTITY_INSERT during seeding with EntityFramework 6 Code-First

后端 未结 9 716
遥遥无期
遥遥无期 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 10:47

    I created an alternate constructor for my DbContext that takes a bool allowIdentityInserts. I set that bool to a private field of the same name on the DbContext.

    My OnModelCreating then "unspecifies" the Identity spec if I create the context in that "mode"

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove();
    
            if(allowIdentityInsert)
            {
                modelBuilder.Entity()
                    .Property(x => x.Id)
                    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
            }
        }
    

    This allows me to insert Ids without changing my actual database identity spec. I still need to use the identity insert on/off trick you did, but at least EF will send Id values.

提交回复
热议问题