Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnModelCreating - forcing new creation

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?

like image 211
Goran Avatar asked Nov 21 '12 12:11

Goran


1 Answers

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.

like image 152
Ladislav Mrnka Avatar answered Sep 30 '22 03:09

Ladislav Mrnka