MySQL Database with .NET Core 6 and Entity Framework

In this article I am going to teach you how to connect MySQL Database with .NET Core 6 using Entity Framework.
Prerequisites
- MySQL Server — Here we use XAMPP.
- Visual Studio 2022
- .NET Core 6
Step 1 - Create a new project using Visual Studio 2022
Open Visual Studio -> Create New Project -> Select C# as the language -> Type “mvc” -> Select ASP .NET Core Web App

Enter a name for the project and then select .NET 6.0 as the target framework, select None as the authentication because we are not going to deal with authentication and then enable Configure for HTTPS. Finally create the new project.

Step 2 — Install Required Packages
After creating the new project now we are going to install all the required packages to our project. To install packages to project you have to follow below steps.
Open your project in Visual Studio -> Tools -> NuGet Package Manager-> Manage NuGet Packages for Solution…
Then go to browse and install below packages.
- Microsoft.EntityFrameworkCore (In this project we are using version 6.0.3)
- Microsoft.EntityFrameworkCore.Tools (In this project we are using version 6.0.3)
- Pomelo.EntityFrameworkCore.MySql (In this project we are using version 6.0.1)

Step 3 — Create a Global Imports file

Note — “BulkyBookWeb” has to be changed according to your project name.
Step 4 — Create a Model Class
Here we create a category model and that model consists all the properties about that model. For that create a new class file called “Category.cs” inside the Models folder in your project.

Note — namespaces can be changed according to your project name and folder names.
Step 5 — Create DBContext and Add Connection String
Create a new folder called “Data” in root directory and create a new class file called “ApplicationDbContext.cs”.

Then we have to create the connection string in our project. Connection string is used to represent all the credentials to connect with database. We can directly put that string when we need it. But since it is a sensitive data we are put it in our appsettings.json
file.

Note — Database name, Username and the password can be changed according to your Database server.
Step 6— Configure application to use MySQL Database
Open Program.cs file and make following changes.

Step 7 — Add Migrations and Update the Database
First open XAMPP and start MySQL. Then go to -> Tools -> NuGet Package Manager-> Package Manager Console. Then type the following command to create migration.

Now You can see there is a new folder called Migrations
and inside that folder we can see some files. Those files represent all the details about relevant Database Migration.

As the final step now you have to update the database according to the migration. To update the database run following command.

Now go to Database. You can see there is a new Database and inside that database we have the new table.