OnModelCreating - forcing new creation

ef-code-first, entity-framework, entity-framework-5

Solution

OnModelCreating will always be called only once. If you need to recreate model you must manually create `DbModelBuilder`.

var builder = new DbModelBuilder(DbModelBuilderVersion.Latest);
// setup whole model
DbModel model = builder.Build(connection);
DbCompiledModel compiledModel = model.Compile();
// cache compiledModel for future usage - compilation is very expensive

var context = new DbContext(compiledModel);

You should try to avoid this. Identity insert doesn't work very well with EF so you will most probably have to insert data directly with SQL and that doesn't need changing the mapping.

Problem

In some situations, during the application run, I need to turn on identity insert: ``` modelBuilder.Entity<Activity>().Property(p => p.Id).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None); ``` But, since OnModelCreating is executed only once, what would be the best way to achieve this? Is it possible to recreate model?

Original source