EF Code, when changes in models are needed, any way not to delete DB?

I'm trying to get control of Code First, and so far every time I make changes to the model, I need to reset and recreate the database. What about the data that is currently in the database? I just find it annoying that I have to do it every time and not do it for a good web approach, if you are 100% not sure that you will never have to make changes like adding a new column to the table. Is there any other way to prevent this?

+4
source share
2 answers

By default, the database initializer is set to DropCreateDatabaseIfModelChnages. you can set the database initializer to zero to avoid re-creating,

Database.SetInitializer<YourContext>(null); 

Another option is to use Database Migrations to update the database without having to recreate it.

+1
source

If you are trying to save test data during development, consider using the Seed method for IDatabaseInitializer (i.e. the database initializer). The Seed method is called during itialization (after applying any model changes) and fills in any test data that you specify.

The best way to specify which initializer you want to use EF is in the global.asax.cs file.

Here is an example:

[Global.asax.cs]

 Database.SetInitializer<MyApplicationDbContext>(new MyApplicationDbContextInitializer()); 

[MyApplicationDbContextInitializer.cs]

 public class MyApplicationDbContextInitializer : DropCreateDatabaseAlways<MyApplicationDbContext> { protected override void Seed(TitleDB context) { context.Products.Add(new Product { Id = 1, Name = "Foobar XL" }); context.Products.Add(new Product { Id = 2, Name = "Foobar LG" }); context.Products.Add(new Product { Id = 3, Name = "Foobar MD" }); context.SaveChanges(); base.Seed(context); } } 
+1
source

Source: https://habr.com/ru/post/1416174/


All Articles