Using MySQL with Entity Framework

Download full source code.

Over the past few months, I’ve been writing posts about using various databases with .NET and in particular Entity Framework.

Not it’s the turn of MySQL.

I may be wrong on this, but I recall a time when MySQL was more popular. If you were on Linux it was part of the popular LAMP stack. But it seems to have declined in popularity with Postgres taking its place.

But no matter, here is a simple example using MySQL and Entity Framework.

Docker

As with the other database posts, I don’t actually install the database on my computer as such, instead, I run it in Docker.

Here is the command to start MySQL -

docker run -p 3306:3306 --name local-mysql -e MYSQL_ROOT_PASSWORD=my-secret-pw mysql:latest

That’s all you need to start it. Port 3306 will be available on your host.

The Application

The application is a simple console app that uses Entity Framework to connect to the MySQL database, seed it, print out the rows, and get a row count.

The only parts that are different from any other database application you have worked on are the connection string, DbContext, and the NuGet package needed.

To use MySQL with Entity Framework you need to install the MySql.EntityFrameworkCore NuGet package.

You can do this in the Package Manager Console with the following command:

dotnet add package MySql.EntityFrameworkCore

In the DbContext override the OnConfiguring method as shown here -

1protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
2{   
3    optionsBuilder.UseMySQL("Server=localhost;Database=SalesDb;User=root;Password=my-secret-pw");
4    
5    base.OnConfiguring(optionsBuilder);
6}

That’s really about it.

The attached zip has a fully working example.

Download full source code.

comments powered by Disqus

Related