Skip to main content

Command Palette

Search for a command to run...

Connecting MYSQL Database to ASP.NET Project

Updated
•1 min read•View as Markdown
  1. Install Pomelo.EntityFrameworkCore.MySql from Nuget package manager console

    1. Set the connection string in appsettings.json as

       {
         "Logging": {
           "LogLevel": {
             "Default": "Information",
             "Microsoft.AspNetCore": "Warning"
           }
         },
         "AllowedHosts": "*",
         "ConnectionStrings": {
           "dbcs": "Server=localhost; Port=3306; Database=bulky; User=root; Password=;PersistSecurityInfo=True;"
         }
       }
      
    2. Change the Program.cs file as required to get Mysql connection string

      
       var builder = WebApplication.CreateBuilder(args);
      
       // Add services to the container.
       builder.Services.AddControllersWithViews();
      
       // Register IConfiguration and read connection string from appsettings.json
       builder.Services.AddSingleton(builder.Configuration);
      
       // Configure DbContext with MySQL
       builder.Services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
       {
           options.UseMySql(builder.Configuration.GetConnectionString("dbcs"),
               new MySqlServerVersion(new Version(8, 0, 28))); // Adjust the version according to your MySQL server version
       });
      
       var app = builder.Build();
      
    3. Now add-migration and update the database.

87 views

More from this blog