How to Implement Code-First Migrations with Entity Framework Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video i will show you how to use entity framework core migrations migrations allow creating a database from a set of c-sharp classes that we call a model as the model evolves migrations allow keeping the model in sync with the database in this tutorial i will show you how to enable migrations in visual studio how to create a database using a migration and how to revert or roll back changes using migrations let's get into it you can work with efcor in two ways you generate a model from an existing database this approach is called database first or you end code a model then you use migrations to create a database this approach is called code first with the code first approach there is a challenge to keep the database schema up to date with the current state of the model migrations will help with that let's start by creating a project in visual studio i'm going to create a new console app the type of app is not that important the goal is to demonstrate migrations i will use a local instance of sql server as the database in order to work with sql server i'm going to need to install two nuget packages let's open the nuget package manager window and search for entity framework the first package we need is microsoft dot entity framework core dot sql server this package helps connect to the database the second package we need is microsoft dot entity framework core dot tools this package allows running migrations from the nuget package manager window in visual studio we will see some of the comments later the packages are installed in order to work with entity framework we need to create a model i will create a database that stores jobs for a job listing website let's create a new folder i will name it models inside this folder i'm going to add a new class and i name it job let's introduce some properties that describe a job the id property is the primary key a job has a title and a description next we need a data context let's add a new folder i will name it data inside this folder i create a new class i call it job context a data context must inherit from the db context class next i expose a db set property of jobs this property can be used to query jobs in the database next i'm going to override a method named unconfiguring this method allows to configure the database needed by the context the method use seeker server on the db context options builder allows setting the connection string to the database this connection string points to my local database the initial catalog parameter will be the name of the database now it's time to create the database using our first migration for that i go into the menu and i select tools then nuget package manager and then package manager console in the package manager console the command we need is add dash migration i need to provide a name for the migration i name it create database if i execute this command you can see that the migration has been created what exactly is a migration if you look into the project folder you can see that a migration folder has been created and it has two files inside the first one is a file with a timestamp and the name of the migration the second one is a file that starts with the job context and then model snapshot the migration file has two methods an app method and a down method the up method you can see that this code will create a table name jobs with the id a title and a description and the primary key will be on the id column the down method as code needed when reverting the migration this code will drop the jobs table the snapshot file has code that represents the state of the model after applying a migration this file helps entity framework to compute the next migration let's return to the package manager console i use another command update database you can add the parameter verbose to output the generated sql statement let's execute this you can see that the migration has been applied if we take a look into the output window you can see the sql statement for creating the jobs table you can also see the statements for installing data into a table named ef migrations history let's go to the database you can see that there is a job listing database the database has two tables the first one is ef core migration history ef core will use this table to compare the migrations inside it to the ones in the project if it detects that there are migrations in the project that are not in the history table it will apply them the second table is mapped to the job entity in our model you can see that it has all the columns we define into the model now let's say we want to store the date at which a job was created for that i add a new date time property i name it creates at if we want this change to be reflected in the database we need to create a new migration i name it add created at column if we take a look at the migration file you can see in the app method that the code will add a new column in the jobs table in the down method the code will drop the column ef core knows what changes to generate by comparing the snapshot and model let's apply this migration if we take a look into the database you can see that we have a created add column now let's introduce a change let's say that the created at column can accept null values i'm going to update the job class and make created art nullable then i'm going to create a new migration make created add nullable let's take a look at the migration the code will alter the column created at and make it nullable but let's imagine that we don't want to apply this migration how can we revert it we will use the command remove migration this will remove the last migration from the project if the command runs successfully you can see in the output remove migration and revert the model snapshot if you take a look into the migration folder you can see that the migration has been deleted and the snapshot has also been update in the snapshot you can see that the created field is required it doesn't accept null that's the behavior we expect when reversing the migration but the model didn't change i can create the migration again this time let's actually apply it against the database if we check the database you can see that the created at column now accepts null values let's pretend again that applying this migration was a mistake how can we revert a migration that is already been applied we can use the remove migration and provide the parameter force this will undo the migration in the database and we also remove the migration from the project let's execute the migration you can see that it says that it reverts the migration and remove it if we check in the project folder the migration is gone if we check in the database the created at column is back to its previous state let's update the job class and restrict the size of the title by using the max length attribute i create a new migration limit title size to propagate changes to the database you can see that i receive a warning stating that i may lose some data this is normal because i'm changing the size of a column in the database if there is data with a title bigger than the max it will be truncated in the migration file in the app method the title will change it will be limited to 100 characters i'm going to apply the migration with the update database command if i check into the database you can see that the title is now restricted to 100 characters so let's do the same for the description i create a new migration and i receive the warning again because the operation may result in data loss let's apply the migration if i refresh the database you can see that the restriction has been applied to the description column now let's say you need to go back in time before those changes were done if you look into the migration history if you don't want to take into account the two last migrations you will need to use the update database command by the way if you want to get the list of all migrations from the console you can use the get migration command it will show you all the migrations in the folder i use the update command but this time i supply the migration parameter the parameter is the name of the migration i want to go back to in this case i want to go back to add created add column if i execute this command you see in the output it reverts the two lattice migrations if i go into the database in the migration history table the migrations after add created at column have been removed and if i refresh the columns the lattice changes have been cancelled the migration themselves have not been deleted so they're just they were just reverted let's say i want to fix a bug or something i can do that and then use the update database command to apply the migration again so if i go into the database in the migration history you can see that the migration are back if i refresh the columns you can see that the restriction appear again let's say i want to create a view i will need to use some raw sql for that i'm going to use the command add migration i name my migration create view you will notice i didn't change anything to the model so this will create an empty migration you can see that the app method and the down method are empty i'm free to add some sql statements here let's create the sql statement for creating a view the name of the view is get all data to keep things simple i will fetch all the data from the jobs table next i can invoke the sql method on the migration builder and pass the query statement in the done method the sql is pretty simple i drop the view i also invoke the sql method on the migration builder that's it the migration is created now i can apply the migration if i execute this you can see that the migration has been applied so let's check into the database you can see the view get all data of course i'm not going to execute this because i haven't insert any data sometimes you can't apply migrations in a production environment you will need to generate a sql script for a database admin for that i will use the command script migration if i execute this command it creates a script that can be used by someone to execute it against the database or to perform some kind of fine tuning this concludes this video about migrations i hope this tutorial was helpful to you if it was please like the video and subscribe for more thanks for watching see you next time
Info
Channel: Tech With Pat
Views: 6,883
Rating: undefined out of 5
Keywords: entity framework core code first migrations, entity framework, code first, entity framework core, code first migrations, entity framework core migrations, entity framework tutorial, entity framework migrations
Id: W9yVjry3VSQ
Channel Id: undefined
Length: 15min 59sec (959 seconds)
Published: Sun Mar 06 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.