easy database migrations with c# and fluentmigrator
TRANSCRIPT
Easy database migrations with C# and
FluentMigratorPresented by : Safal Mahat
What is migration?Database migrations are an increasingly common pattern for managing and automating the creation of your projects database schemas.
Typically each migration has 3 elements:
1.A Unique Id – each new migration is given a numeric identifier higher than the previous one.
2.An UP component – describing the table / row / column / key – you want to create.
3.A DOWN component – which exactly reverses the change you’re are making in the UP component.
But why?• No separate SQL scripts, db exports etc. All database migrations
are contained within the project and can be reviewed and managed by the team – No DBA Required.
• Easy deployment onto as many servers as required – most medium to large projects will have a number of environments, minimally dev, test and live.
• As the project grows, database migrations can be created as required, meaning you can easily rollout new changes to live projects.
• Easy rollback – if you rollout a patch containing a migration, you can instantly roll it back without discovering you don’t have rollback scripts.
• Roll outs to the live db are usually possible with no downtime.
Introducing FluentMigrator• FluentMigrator is a package that allows you to create “fluent”
migrations within Visual Studio.
• It uses fluent interface to manipulate database.
• The easiest way to get Fluent Migrator and keeping up-to-date is from the nuget packages.
• In the package manager console, type: PM> Install-Package FluentMigrator
• Also if you would want to run migrations from the command prompt, nant or msbuild you need the Tools package: PM> Install-Package FluentMigrator.Tools
Creating migrations• The basic unit of FM is the
Migration abstract class. Your migrations will derive from this class and implement two methods - Up() and Down().
• You also need to define the Migration attribute with a unique identifier, an incrementing value for the ordering of your migrations.
Running the migrationsThere are many ways to run the database migration:
• Command Line
• PowerShell script
• MSbuild task
• NAnt task
• FluentMigrator.Runner PM>Install-Package FluentMigrator.Runner
Best Practice• Keep all the migration classes in a
separate project.
• Number the migration classes in line with their migration number ie Mig012_CreateTableX – makes it easier to manage them once you have a few migrations.
• It’s a common practice to use a numbered date format such as yyyyMMdd for naming the class as well as for the migration number.
ConclusionsFluentmigrator takes a lot of the pain out of managing your database schema over multiple environments.