A brief description of how to create a .net web api project with mysql and necessary dependency.
- Create a ASP.NET Core Web API project on .NET 6.0
- Install these NuGet packages.
- Microsoft.EntityFrameworkCore.Design
- Microsoft.EntityFrameworkCore.Tools
- MySql.EntityFrameworkCore
- Scaffold-DbContext from the existing MySql database.
Scaffold-DbContext "server=servername;port=portnumber;user=username;password=pass;database=databasename" MySql.EntityFrameworkCore -OutputDir Entities -f
-
If
MySql.EntityFrameworkCore
throws and error while scaffold then most probably it's for NuGet packages version. Downgrade all three packages into version 5.0.16 as mentioned in this documentation.After successful scaffolding upgrade these packages back to the their latest versions. -
After successfully scaffolding we'll find connection string into newly created DbContext file.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{ optionsBuilder.UseMySQL("server=localhost;port=3306;user=root;password=;database=database");
}
}
- But it's not appropriate that the connection string to the database is specified in the OnConfiguring method. So we'll move connection string into
appsettings.json
file.
"ConnectionStrings": {
"DefaultConnection": "server=localhost;port=3306;user=root;password=;database=demo;"
}
- Then, in the
Program.cs
, we'll add as a service to refer DBContext, and that must have the reference ofDefaultConnection
specified in theappsettings.json
file.
using Microsoft.EntityFrameworkCore;
using dotNetWithMySqlAPI.Entities;
using MySql.EntityFrameworkCore.Extensions;
builder.Services.AddEntityFrameworkMySQL().AddDbContext<dotnetapiContext>(options => {
options.UseMySQL(builder.Configuration.GetConnectionString("DefaultConnection"));
});
- Now add a api controller using the model and run the application.