Akshay Kumar Sharma
Akshay Kumar Sharma

Reputation: 271

Update database from CodeFirst in EF6 without wiping out data

I want to use Code First Technique of EF6 but when i made changes to table, it drops the database and recreates it, wiping out all data. Is there any way to stop this from happening?

My Code :

Database.SetInitializer<EmployeeDb>(new DropCreateDatabaseIfModelChanges<EmployeeDb>());

Upvotes: 0

Views: 961

Answers (1)

Murat Seker
Murat Seker

Reputation: 916

These are the strategies for database initilization in code first approach:

  1. CreateDatabaseIfNotExists: This is default initializer. As the name suggests, it will create the database if none exists as per the configuration. However, if you change the model class and then run the application with this initializer, then it will throw an exception.
  2. DropCreateDatabaseIfModelChanges: This initializer drops an existing database and creates a new database, if your model classes (entity classes) have been changed. So you don't have to worry about maintaining your database schema, when your model classes change.
  3. DropCreateDatabaseAlways: As the name suggests, this initializer drops an existing database every time you run the application, irrespective of whether your model classes have changed or not. This will be useful, when you want fresh database, every time you run the application, like while you are developing the application.
  4. Custom DB Initializer: You can also create your own custom initializer, if any of the above doesn't satisfy your requirements or you want to do some other process that initializes the database using the above initializer.

Here, it can give you general idea and how to use one of these approaches.

Due to your comments CreateDatabaseIfNotExists helps you. With this approach when you add or remove your model classes, your db will be updated and your data will be stable.

Here you can find examples both Context constructor and config file

Another topic about this on stackoverflow.

Upvotes: 1

Related Questions