(C# EF Core) MySQL Database Connectivity in an ASP.NET Core Razor Page Project

These are the minimal steps for connecting to a MySQL database server with EF Core. A simple application of one textbox form has been used to demonstrate how records can be inserted into a table in a MySQL database. The tables and database are created automatically by EF Core on the basis of code first approach.
(Rev. 04-Jun-2024)

Categories | About |     |  


Things you will Need

These must be available -

  1. MySQL Server must be running and accessible.
  2. Your UserID, Password, Server IP must be available.
  3. Verify that you can connect to the MySQL server with your UserID and Password.

Video Explanation

Please watch the following youtube video:

Add Nuget Package

The current version provided by Oracle Corp. at the time of writing of this article is 5.0.x - so your project should be configured for .NET 5. The best way to ensure this is to use Visual Studio 2019 instead of 2022. ONCE THEY RELEASE VERSION 6, THEN YOU CAN USE VISUAL STUDIO 2022 BY FOLLOWING THE SAME STEPS WITHOUT ANY CHANGE. If you are learning through our course then use the attached download, which will work out of the box.


Run this on package manager console -

PM > Install-Package MySql.EntityFrameworkCore -Version 5.0.8

Configure your Startup.cs File

This is the bare minimum startup.cs file that will work for our case -

// Visual Studio 2019 with .NET 5 used 

// namespaces 
using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.DependencyInjection;

// using MyRazorApp.Pages.Models; 

using MySql.Data.MySqlClient;

namespace MyRazorApp

  public class Startup

    public void ConfigureServices(IServiceCollection services)

      // Install-Package MySql.EntityFrameworkCore -Version 5.0.8 
      MySqlConnectionStringBuilder conn =
          new MySqlConnectionStringBuilder()


      // any suitable name can be given for your database 

      // EF Core code-first will create it for you 

      // TODO 
            Database = "mydb",
            UserID = "-your-own-",
            Password = "-your-own-",
            Server = ""

          opt => opt.UseMySQL(conn.ConnectionString)



    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)


      app.UseEndpoints(endpoints =>






Following is the Program.cs file - the same as visual studio creates for you -

// Program.cs as created by visual studio 
using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Hosting;

public class Program

  public static void Main(string[] args)



  public static IHostBuilder CreateHostBuilder(string[] args) =>
        .ConfigureWebHostDefaults(webBuilder =>



Model and Context Classes

Use these simple model and context classes

// model class 
public class Item

  public int ID { get; set; }

  // better to specify - TINYTEXT, TEXT, MEDIUMTEXT, LONGTEXT 
  [Column(TypeName = "TEXT")]
  public String Name { get; set; }

// dbcontext 
public class MyProjectContext : DbContext

  public MyProjectContext(DbContextOptions options) : base(options)

    // IMPORTANT: you will get exception here 
    // if your MySql connection fails 


  // MUST be PLURAL 
  public DbSet<Item> Items { get; set; }

The Index Razor Page

Use this for the Index.cshtml file


// your namespace - mine is MyRazorApp 
@model MyRazorApp.Pages.IndexModel

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<form method="post">



        <label asp-for="DataItem.Name"></label>

        <input asp-for="DataItem.Name" />



        <input type="submit" />





Use this for the Index.cshtml.cs file

// use your namespace names - mine is MyRazorApp 
using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.RazorPages;

using MyRazorApp.Pages.Models;

using System;

using System.Threading.Tasks;

namespace MyRazorApp.Pages

  public class IndexModel : PageModel

    readonly MyProjectContext _ctx;

    public IndexModel(MyProjectContext ctx)

      _ctx = ctx;


    public Item DataItem { get; set; }

    // used for displaying message upon redirect 
    public String Message { get; set; }

    // on post handler 
    public async Task<IActionResult> OnPostAsync()



        await _ctx.SaveChangesAsync();

        Message = "Saved OK!";


      catch(Exception ex)

        Message = "failed: " + ex.InnerException.Message;


      return RedirectToPage();




Run the Project

Run the project to see that you can add records!

I am appending my csproj file. I created my project with Visual Studio 2019. But this opens and compiles in Visual Studio 2022 also

<Project Sdk="Microsoft.NET.Sdk.Web">


    <PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.8" />


This Blog Post/Article "(C# EF Core) MySQL Database Connectivity in an ASP.NET Core Razor Page Project" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.