How To Connect MySQL In ASP.NET Core

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

  1. MySQL (You can get MySQL IDE – MySQL Work Bench here).
  2. NET CORE Environment Setup. (you can get it here).
  3. Visual Studio 2015 or Visual Studio 2017 (download VS 2017 here).
  4. 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.

ASP.NET Core

 

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

ASP.NET Core

ASP.NET Core

 

Clean build and run the Application for testing.

ASP.NET Core

 

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;”.

ASP.NET Core

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

ASP.NET Core

Similarly, we run SQL queries on CLI, create tables, and insert data into it.

  1. Now, let's check with MySQL workbench IDE
  2. Select the Query template. Write SQL queries in the query editor. Click the Lighting icon. 

    ASP.NET Core

    On the top menu.

    ASP.NET Core

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

ASP.NET Core

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

ASP.NET Core

ASP.NET Core

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

ASP.NET Core

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

ASP.NET Core

ASP.NET Core

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.

ASP.NET Core

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.

ASP.NET Core

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.

ASP.NET Core

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.

ASP.NET Core

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.