Skip to main content

Posts

Showing posts from December, 2017

Entity Framework Code First Migrations

This post details the setup process for Entity Framework code first migrations. Assume a new project with a  User  entity, with just 2 properties: Id and Name. The database schema is yet to be created. Creating the Schema Install the Entity Framework package, through the Nuget package manager or other means - more information on the package can be found on the project site Add a UserConfiguration  file to control the mapping between entity and schema Add IDataContext  and DataContext files, here every persisted entity must be declared as a DbSet and the corresponding configuration file must be added to the model builder as shown Add a connection string in the web config file, to an existing database In the package manager console, select the project where the Entity Framework package has been installed. Type update-database  and run. This will create the schema in the database given in the connection string Updating the Schema Now, make a ...

Database migrations with Fluent Migrator

Fluent Migrator makes the process of writing database migrations much easier and less error prone by removing the need to write sql scripts. Instead, all schema changes are written in C# files, utilising methods in the Fluent Migrator library. This post describes the required steps to setup Fluent Migrator, in the context of creating a user table. Install the Fluent Migrator package into the migrations project - more information on installation can be found on the project site In an appropriate location, add a new C# file to become the first migration The file should implement Migration, from the Fluent Migrator package Decorate the class with the Migration attribute, and as this is the first migration in the project it takes the argument 1 Every migration class requires an Up and a Down method, to commit the schema changes and rollback if an error occurs in the process In the Up  method, a  User  table is scripted for, with an Id field (a primary key) an...