Objective
In this article, we are going to understand how to connect .NET CORE Application with MySQL and read data from MySQL, using the .NET Core MySQL connector.
Prerequisites
- MySQL (You can get MySQL IDE – MySQL Work Bench here).
- NET CORE Environment Setup. (you can get it here).
- Visual Studio 2015 or Visual Studio 2017 (download VS 2017 here).
- MySQL database.
Steps to create a .NET Core Web app with Visual Studio 2017
Go to File → New Project → Select Web from templates → Choose ASP.NET Core Web Application (.NET Core).
Provide the name for the Web app and click OK.

Select the Web Application template and click OK. It will create a .NET Core Web app for you.


Clean build and run the Application for testing.

Set up MySQL database
To create the MySQL database, we must have an IDE for MySQL, or we need to have MySQL CLI. We can create the database, either with IDE or using CLI commands.
We can create the database in both ways. Let’s check out CLI first.
To create a database, using CLI, we first need to log in with the password, which we have provided at the time of installation.
After login, type the command “create database MusicStoreDB;”.

To check if DB is created or not, run the command given below.

Similarly, we run SQL queries on CLI, create tables, and insert data into it.
- Now, let's check with MySQL workbench IDE
- Select the Query template. Write SQL queries in the query editor. Click the Lighting icon.
On the top menu.

After creating a table, insert records in created DB, run Select query on the table.

For now, we did for a single table only. We are done with the database creation and data insertion.
Connect with MySQL
To connect with the MySQL database, we must have some NuGet installed in our Application.
Go to Application → right click on project name → select Manage NuGet Packages → Type MySQL.Data


Go to Project root → appsettings.json → enter the connection string, as shown below.

Create a new folder Models and add Class ‘MusicStoreContext’& ‘Album’ in it.


Add Album properties in Album class.
namespace NetCoreWebApp.Models
{
public class Album
{
private MusicStoreContext context;
public int Id { get; set; }
public string Name { get; set; }
public string ArtistName { get; set; }
public int Price { get; set; }
public string Genre { get; set; }
}
}
Create a new MusicStoreContext class, which will contain the connections and MusicStore data entities, as shown below.
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
namespace NetCoreWebApp.Models
{
public class MusicStoreContext
{
public string ConnectionString { get; set; }
public MusicStoreContext(string connectionString)
{
this.ConnectionString = connectionString;
}
private MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
}
}
To use context in our Application, we need to register the instance as a Service in our Application. To register context, we need to add one line of code in ‘startup.cs’ file under ‘ConfigureServices’ method.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NetCoreWebApp.Models;
namespace NetCoreWebApp
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.Add(new ServiceDescriptor(typeof(MusicStoreContext), new MusicStoreContext(Configuration.GetConnectionString("DefaultConnection"))));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
Fetch data from My SQL database
To get the data from the database, we need ‘GetAllAlbums()’ method, our DB context, add ‘GetAllAlbums()’ method in “MusicStoreCotext” class.
public List<Album> GetAllAlbums()
{
List<Album> list = new List<Album>();
using (MySqlConnection conn = GetConnection())
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("select * from Album where id < 10", conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new Album()
{
Id = Convert.ToInt32(reader["Id"]),
Name = reader["Name"].ToString(),
ArtistName = reader["ArtistName"].ToString(),
Price = Convert.ToInt32(reader["Price"]),
Genre = reader["genre"].ToString()
});
}
}
}
return list;
}
Now, we need a controller to manage our code. Add a controller with the name AlbumsController.

Add the code given below in Album Controller to get the data from DB.
namespace NetCoreWebApp.Controllers
{
public class AlbumController : Controller
{
public IActionResult Index()
{
MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(NetCoreWebApp.Models.MusicStoreContext)) as MusicStoreContext;
return View(context.GetAllAlbums());
}
}
}
After adding the controller and code, we require a view to display the data to the end-user. Create a folder under Views with the name Albums. Right-click on the Albums folder and add new view Albums.
Select the Layout page by clicking the button. Now, click add.

You can create a view from by selecting the data model in the dropdown, or you can create a blank view with the default index name and add the code, as shown below.

To route to our Album action, we need to update Startup.cs and add the Album controller name, so we after running an app directly. We get the “Album/index” page.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Album}/{action=Index}/{id?}");
});
Now, just run an Application, and we will get the output, as shown below.

Conclusion
In this article, we have seen how to make a connection with the MySQL Server database. In the case of remote, we need to update the connection string with an appropriate server name and the port name.
Feel free to share suggestions and feedback.

Irina HagmanPosted Apr 9, 2023, 7:29 AM
Can you please update to a new version?
Irina HagmanPosted Apr 9, 2023, 7:28 AM
ILoggerFactory does not containt AddConsole
gilbert senyonjoPosted Aug 11, 2021, 2:44 PM
Thank you very much for this article. Very beginner friendly. Looking forward to next steps. For my fellow newbies, take a look at my final code if you're getting challenges. Its here: https://github.com/rsgilbert/AspMySql. Right now there are only two commits but the codebase may grow in the future.
chebbi siwarPosted Mar 27, 2021, 12:54 PM
Hi everyone , i'm getting an error in the view called : System.NullReferenceException: 'Object reference not set to an instance of an object.' i d'ont know how to solve it ..
Tony PitwoodPosted Apr 22, 2020, 4:30 AM
Hi Abhijit, I'mgetting an error CS0116 Namespace cannot contain ... methods on this line public List<Album> GetAllAlbums() Is there a possibility I could view your source? Thanks, Tony Pitwood
Jack RobinsonPosted Mar 5, 2020, 10:00 PM
Thanks for post this article
said aksaPosted Sep 8, 2019, 2:05 PM
Hello Mr Abhijit Patil, i'd like to know if its possible to create the Album table from the model. That means how to make the inverse. i mean when to make: add-migration and update database , the table will be created.Thank you in advance.
Sushil KumarPosted Jul 27, 2019, 12:02 PM
Yes, we can use Entity Framework, go to this link to integrate ASP.NET core, Entity Framework and MySQL. http://thesushil.com/2019/07/asp-net-core-entity-framework-core-and-mysql-integration/
Ben HayatPosted Mar 19, 2019, 1:53 PM
But why didn't you use Entity Framework Core that the old style of ADO.Net?
Александр ГалинPosted Jan 30, 2019, 6:33 AM
Thanks a lot, it helped me create a simple database connection.
Ahmet BilgicPosted Sep 2, 2018, 8:21 AM
It gives me this Error, can you help me; MySqlException: Access denied for user ''@' (using password: NO)
Vijaya BollavarapuPosted Aug 26, 2018, 11:44 PM
You might think why am I commenting where I could just leave. I have spent 2 hours almost.
Vijaya BollavarapuPosted Aug 26, 2018, 11:44 PM
Frankly saying. Your code is completely unfriendly and useless. It has wasted my time a lot. Cant understand as a beginner. Anyway appreciate your efforts.
Richardson dos Santos NevesPosted May 2, 2018, 11:50 AM
Avinash Barnwal For .Net Core 2.x I?ve migrate my repository pattern (and some other codes) to use Async Poco. Change all related code to async generate some effort.
Richardson dos Santos NevesPosted May 2, 2018, 11:47 AM
Nice post. But for .Net Core 2.x I?ve migrate my repository pattern (and some other codes) to Async Poco.
Avinash BarnwalPosted Oct 21, 2017, 1:02 PM
Does it still work with .netcore2.0 ?