Running migration

Running .NET CLI commands is straightforward. There are various commands that helps you with adding migration, removing migration, updating the database, dropping the database, and so on.

Let's start by creating the initial migration first. To create the initial migration, you have to go to the root folder path of your data access layer project and run the following:

dotnet ef migrations add Initial 

In the preceding command, Initial is the name of the migration. When the command is executed, it actually searches for the class derived from the DbContext base class, and creates the database and tables for the connection string defined. Otherwise, the local DB store will be used.

On running, a new Migrations folder is created containing the file suffix Initial.cs, as shown in the following image:

Each migration class has two methods, namely, Up and Down, which are used to apply or revoke changes.

To create a database or to apply changes on the existing database, we have to run the following command:

dotnet ef database update -verbose

In the last command, -verbose is the switch used when you want to know the details of the operation being executed.

Now, once this command is executed successfully, our database and tables will be created, as shown in the following screenshot:

If you notice, in the last screenshot, there are some AspNet* tables, which are not defined in our DataContext class, but created automatically. The reason is the IdentityDbContext class, which takes the IdentityUser type. To study more about IdentityUser and IdentityDbContext, please refer to Chapter 10, Security Practices with .NET Core. Another important thing to note is the _EFMigrationsHistory table. This is the default table created after running the Entity Framework migrations and contains the entry of each migration. When running the migrations from .NET CLI command, Entity Framework actually checks the last migration entry in this table, and executes the corresponding migrations accordingly. To learn more about migrations, please refer to this link: https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/migrations.

The next screenshot shows the final structure of the data access layer:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.5.201