Use MySQL in ASP.NET 6 with Entity Framework

Connect MySQL database to ASP.NET 6 project with Entity Framework

Original YouTube Logo

Article have related YouTube video

Connecting to a MySQL database with ASP.NET 6 can be a little trickier than first anticipated. But fear not, the perfect solution is here. The most important thing is to choose the correct versions of the NuGet packages from Microsoft and Oracle else you will get some error messages that can give you headache for hours.

16-06-2022 |

ASP.NET Core
MySQL
Entity Framework

So there is minimum four essential NuGet Packages you want to use for connecting to your MySQL database using Entity Framework in ASP.NET Core. Two packages from Oracle who own MySQL and two packages from Microsoft who is the creator of Entity Framework. The most important thing when installing the NuGet Packages is to choose the right versions. Right now when writing this article the newest version is 6. However if you use both the packages from Oracle and the packages from Microsoft in version 6 it will not work. So the important thing is that you choose the newest version 5 to all the packages.

The NuGet packages:

  • MySql.EntityFrameworkCore (5.0.13)
  • MySql.Data (8.0.29)
  • Microsoft.EntityFrameworkCore (5.0.17)
  • Microsoft.EntityFrameworkCore.Tools (5.0.17)

After installing the NuGet packages create a new folder in the same level as the "Pages" folder. Call the new folder "Model". Inside the "Model" folder we want to add two files. First Create a file called "AppDbContext.cs" and a second file called "Book.cs"

AppDbContext.cs

  
using Microsoft.EntityFrameworkCore;

namespace ConnectToMySQL.Model
{
    public class AppDbContext : DbContext
    {
        public DbSet<Book> Book { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionBuilder)
        {
            optionBuilder.UseMySQL("server=?;database=?;uid=?;pwd=?;");
        }
    }
}


What the "AppDbContext" file will do is to act as a overview over the tables in the database and handle the connection to the database. You need to enter your own connectionstring in the method UseMySQL().

Book.cs

  
using System.ComponentModel.DataAnnotations;

namespace ConnectToMySQL.Model
{
    public class Book
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
    }
}


When you migrate you want to use the build-in console in Visual Studio 2022 called Package Manager Console. The commands for migrating is pretty simple:

Migrations

  
add-migration NameOfMigration
update-database


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