Sunday 25 January 2015

Using Entity Framework Code First Migration Asp MVC

 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–
  1. 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.
  2. 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.
  3. 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.
  4. Enable migrations

    Enable-Migrations
  5. Create migration

    Add-Migration MigrationsName
  6. Create upgrade/downgrade script

    Update-Database

  7. 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:
  8. Create migration

    Add-Migration MigrationsName
  9. Create upgrade/downgrade script

    Update-Database


Share this

0 Comment to "Using Entity Framework Code First Migration Asp MVC"

Post a Comment