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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With