This tutorial shows how to use MySQL database with MySQL Connector in Core.

Before we start it, please make sure you have installed MySQL 5.7, .NET Core, Visual Studio, and also Sakila sample database.

Let’s Get Started

1. The first step is to create ASP.NET Core Web Application and you can name it. For example, we use MvcSakilaCore.

2. Select Web Application template and No Authentication.

3. You will see the project below:

4. Press F5 to run the application:

5. Create a new folder named “Models” where it will store the database access:

6. Installing MySQL Connector/NET Core Package

7. Add Connection string like below

8. Adding data modal classes.

For this example a Film class will be used. It contains the database fields as properties we want to show in our application.

Create a new SakilaContext class that will contains the connections and Sakila database entities:

In order to be able to use our SakilaContext it’s required to register the instance as a service in our application. To do this add the code line in the Startup.cs file:

9. Adding Film Controller

In Solution Explorer, right-click Controllers > Add > New Item… > MVC Controller Class. Name the controller FilmsController:

Change the FilmsController code to this:

10. Creating the Films View

Start creating the Films folder under Views:

In Solution Explorer, right click Views > Films > Add > New Item… > ASP.NET > MVC View Page

Add the following code into the new Index.cshtml view file:

Before run the application, add the Films path to the running url.

In Solution Explorer, right click MvcSakilaCore > Properties > Debug > Launch URL > Films:

Run the application (press F5) and the Films list should be displayed:


Leave a comment

Your email address will not be published.