Friday, June 24, 2011

EF Code-First in the shape of NHibernate - Migrating Changes (4/5)

One of the hassles every application developer might have faced during his/her career is how to best synchronize changes between model and database schemas (versioning problem).Several solutions have been proposed but I personally believe ORM tools should care about this problem in their hearts.

Microsoft's EntityFramework.Migrations is a tool designed for going over such hurdles. Although it has some incompatibilities between different versions of EF, but it looks promising. Technically speaking, the tool checks current object model with the one on database( if any). Any differences are detected and written to a script file and finally migration tool is in charge of running the script file and applies changes to database. 

Note : All you have to do to install is write Install-Package  EntityFramework.Migrations in package manager console.  

There 2 ways to create migration, Manual Migration that uses code-based migration and Automatic. I will pick automatic which is very easy to use.
All we have to write is :

    public class Settings : DbMigrationContext<YourContext>
    {
        public Settings()
        {
            AutomaticMigrationsEnabled = true;
            SetCodeGenerator();
            AddSqlGenerator();
        }
    }

Note: replace YourContext with your DbContext class in your project.


Two commands are handy in migration panel.

  • Add-Migration name that generates a script file for all the changes between object model and database schema.  
  • Update-Migration that pushes all pending changes to the database and applies them on database.

No comments:

Post a Comment