Database, Entity Framework -3

Rose Chang Dycd
3 min readMar 6, 2022

of ASP.NET Core (.Net 6) — 05

Now the program.cs file has been confident, the next step is to create an actual table in the database. When you are using Entity Framework Core, the first that had migrations that you have to run, using Entity Framework to push the changes to a database. Go ToolsNuGet Package Manager → click Package Manager Console.

The first thing to do is to add a migration. Migration is keeping a track of all the changes that are needed. Once the migration is created, you push that migration to the database to create the database or make changes to your table. Enter the command below and press Enter.

If showing you the below error, means that you have to install Microsoft.EntityFrameworkCore.Tools package.

After installed, re-enter the command and start the migration. Showing below means completed. And auto-added to the project.

In migration, we have 2 methods. One is up, and the other is down. The up method is what needs to happen in the migration, the down is if something goes down, we need to roll back the changes.

In the Up method, the table name and the relevant information about the DB column are the same as what you set in both ApplicationDbContext.cs and Category.cs. Technically, there will be no problem and you can enter the command update database in the NuGet Manager Console and run it.

Then you might encounter an error…

Let’s go to appsettings.json file, amend the semicolon to equal marks. (Sorry my bad…)

Done this time!

So we go to SQL server database and check. You will see the Bulky db and 2 tables.

In the Categories table, the columns are what we want.

In the other table, EF will track the migration history of which have been applied here.

So next time you run the update-database, it would not apply to migrate this database. EntityFrameworkCore is pretty smart with all the configuration and cracking that it needs to do so. With that using EntityFrameworkCore, we have created our database and we have added table based on the model inside our main project.

--

--