Daily Archives: November 30, 2013

Code-First Migrations

Continuing my series on Code first development and workflow, in this blog post I’m covering Code First Migrations. Code First Migration facilitates database changes, implemented and completely driven by changes to the properties of the POCO classes, which define the domain specific object model. Code First Migrations fully support the convention over configuration, and agile application development processes. When practicing a code first development strategy, you immediately dive into an iterative and evolutionary approach to development. With the agile approach, the form and functions of the domain model are continuously evolving over the entire course of the software development life-cycle. You need a simple, fast and smooth mechanism, that will automatically apply object model changes to the database, over many iterations of development.

Visual Studio 2013 automatically generates a Migrations folder in the project, to store a time stamped history of all code first migrations generated for the project. Here is an illustration of the Migrations folder in my current project.

Code First Migrations Folder in the Solution Explorer

Code First Migrations Folder in the Solution Explorer

Here is an example of the code generated in a Code First Migration class.

You can customize the code generated by the migrations engine.

To learn more about Code First Migrations see this walkthrough.

Independent and Dependent Foreign Key Properties

As the form and functions of my domain model evolved, I decided that the performance of the navigation properties of the models could be improved by adding the foreign key property directly into the model, and annotating the navigation properties with the foreign key attribute. This not only improved data access performance, it also streamlined much of the user interface development, when I generated controllers and views directly from the models in the MVC 4 and MVC 5 templates.

Here is a link to stackoverflow that has a very good discussion on Independent Associations Versus Foreign Key Associations