Code First Database Initializers
Before understanding code first migrations, let's have a look at Code First Database Initializers provided by Entity Framework. When you follow EF code first approach, then you have three op tions for initializing database as given below–
CreateDatabaseIfNotExists
This is the default database initializer class used by Code First. This class creates a database only if it doesn't exist. This initializer helps you to avoid any accidental deletion of the database.
DropCreateDatabaseWhenModelChanges
This database initializer class drop the existing database and re-creates it if there is a mismatch between the model classes and table schema. This initializer is useful during starting phase of development and testing when models are changing often and there is no concern about the existing database records.
DropCreateDatabaseAlways
This database initializer class always drop and creates a new database, whether it is already present or not with every run of the application. This initializer is useful during testing when you want to run the application with a fresh set of data.
Why Code First Migrations?
The above three database initializing approach become fail when you add new model classes and you want to update existing database without any deletion or change. To achieve this, you need to use EF code first migrations which allow you to update existing database with new model classes changes and your existing database remains same with your database records.
Visual Studio Package Manager Console
To create the database for these two entities within your application, go to the Package Manager Console option as shown below:
Creating New Database
Running Commands
Run the following command to configure migrations within your project and for creating new database.
Enable migrations
Enable-MigrationsCreate migration
Add-Migration MigrationsNameCreate upgrade/downgrade script
Update-Database
Updating Existing Database
Suppose you have added one more class named as Customer into your data model classes as given below:
Running Commands
Now for updating the database with new changes run the following commands as given below:
Create migration
Add-Migration MigrationsNameCreate upgrade/downgrade script
Update-Database
0 Comment to "Using Entity Framework Code First Migration Asp MVC"
Post a Comment