IDENTITY_INSERT during seeding with EntityFramework 6 Code-First

后端 未结 9 723
遥遥无期
遥遥无期 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:13

    For future Googlers, I found the answers suggesting some conditional logic in the OnModelCreating() didn't work for me.

    The main issue with this approach is EF caches the model, so it's not possible to switch identity on or off in the same app domain.

    The solution we adopted was to create a second derived DbContext which allows identity insert. This way, both models can be cached, and you can use the derived DbContext in the special (and hopefully) rare cases when you need to insert identity values.

    Given the following from @RikRak's question:

    public class ReferenceThing
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public string Name { get; set; }
    }
    
    public class MyDbContext : DbContext 
    {
        public DbSet ReferenceThing { get; set; }   
    }
    

    We added this derived DbContext:

    public class MyDbContextWhichAllowsIdentityInsert : MyDbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity()
                        .Property(x => x.Id)
                        .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        }
    }
    

    Which would then be used with the Seeder as follows:

    var specialDbContext = new MyDbContextWhichAllowsIdentityInsert();
    
    Seeder.Seed(specialDbContext);
    

提交回复
热议问题