A little bit of Clean and Migrations.


“ Migrations play a crucial role in development. Without a standardized approach to migrating and seeding data, teams can quickly fall out of sync, leading to inconsistencies and deployment issues.”
Here I will show some setup and best practices for this topic and hope someone to digest these snippets.
On this example I created a class called product
inheriting default values like createdBy , updatedBy, etc.
And on my ApplicationDbContext
I got a code to apply all the configurations that are defined on my infrastructure layer.
Take a look and appreciate at the magic of the applyingConfigurations :)
As your application grows and so your configuration. This is a clean setup that I got from Jayson Taylor Dev (Clean Architecture Template) btw we are using FLUENT API for the models config.
Refresher: The Up
methods are responsible for the additional columns while the Down
method is for rollbacks.
Here I’m renaming the column Description.. I don’t want to dive on the basics because I know you guys already knew it ;)
Once you’re satisfied with your migrations , then update-database
.
Migrations in EF Core cheat sheet (PMC)
Add-Migration insert-migration-name
- will create a migration file.Update-Database
- will update the database based on the pending migrations.Get-Migration
- will list the pending migrations.Script-Migration
- will create a sql scripts for all migrations. (this is useful for companies that have DBA)
Reverting Db Migration
Script-Migration Migration-you-want-to-remove Migration-you-want-to-go-back
- This will generate script that will remove the migration from your DB and also the changes.Remove-Migration
- Will remove the last migration that has been created but not yet applied to the database.
Best practices:
- Never delete migration file manually, use
Remove-Migration
.
Never use
dropColumn
and add another column, useRenameColumn
instead.Keep your migration files clean so that your team will always be in sync.
Use descriptive naming on your migrations.
Use
Get-Migrations
to always check the migrations before applying it.
*Note: it’s best to keep your migration files clean rather than using To
and From
or going back and forth on your migrations, just keep it clean and simple. Remove the migration if it’s not applied, when it’s applied you can update-database where-you-want-to-go-back
or just create a new migration file like ModifyProductTable
when it’s an old migration that you want to remove, like it’s on the middle part. (You wouldn’t want the hassle of recreating your migrations trust me ;)).
I firmly believe that these snippets are very useful on boostrapping your next application!
Subscribe to my newsletter
Read articles from Juan Miguel Nieto directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Juan Miguel Nieto
Juan Miguel Nieto
A software developer trying to write organic blogs.