Setup MySQL connection .NET 7 (ASP.NET Core)

Setup MySQL connection .NET 7 (ASP.NET Core)

Original YouTube Logo

Article have related YouTube video

With Pomelo Foundations MySQL library it is super easy to make a MySQL connection in your ASP.NET Core application. In this example I use .NET 7 and also show how you create the tables using Entity Framework.

28-02-2023 |

ASP.NET Core
MySQL
Entity Framework
.NET

So the first thing we need to do is to install 3 NuGet Packages. So go to the NuGet Package Manager and install the following NuGet Packages:

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Tools
  • Pomelo.EntityFrameworkCore.MySql

All NuGet Packages should be the newest version 7.x.x that you can get. This will make sure that all is compatible with each other and with .NET 7.

Configure your DbContext file

Next we want to setup the connection to the database. You need your server-name, username, password, database-name and the MySQL version that you use.

If you are using phpMyAdmin you can find the MySQL version on the frontpage. In my case it is a server type of MariaDB because I use XAMPP. Currently my version is 10.4.27, however yours might be a different version so check it and make sure you use the right version.

The code inside your context file will look like this:

In this case I have a model called Employees, so lets also create that:

In my case I have set the context file into a folder called Data. And I also created a folder for my Employees model called Model.

Migrate the model

So to check the connection and also add the Employees table to the database, you can use the Add-Migration command to make the migration file, and then finally say Update-Database so that you make the actual migration.

And that is basically how you use Entity Framework with MySQL and setup a MySQL database to your .NET 7 project.


Like what you see?


New C# Learning Area - Free!

Our website now offers a new section on C# theory, including code examples and related video tutorials.

ZetBit

Subscribe to ZetBits Newsletter