11 Handling database migrations
This chapter covers
- Using EF Core’s migration to update a database
- Building a DbContext from an existing database
- Changing a database by using SQL command scripts
- Applying updates to your production database
This chapter covers the three ways of changing the structure of a database. The structure of the database is called the database schema—the tables, columns, constraints, and so on that make up a database. Creating and updating a database schema can seem simple because EF Core provides a method called Migrate
to do it all for you; you create your entity classes and add a bit of configuration, and EF Core builds you a nice, shiny database.
The problem is that EF Core’s Migrate
method hides a whole series of database migration issues that might not be immediately apparent; for example, moving data from one entity class to another entity class can cause loss of data when applying a database schema change. Getting a database change wrong on a database that has live data in it is a scary problem.
I’ve split the chapter into two distinct parts. Part 1 describes all the ways to update a database’s schema when working with EF Core. Part 2 presents the issues around a database schema change, starting with simple changes and working up to the much more complex situations requiring real care to ensure that data isn’t lost.