EF Core + MySQL (Code First) - Quick Cheat Sheet
0) Prerequisites
- .NET SDK installed (
dotnet --info) - A MySQL server you can connect to
1) Install the EF CLI tool (dotnet-ef)
Needed for
dotnet ef migrations ...commands.
dotnet tool install --global dotnet-ef
# update later if needed:
dotnet tool update --global dotnet-efVerify:
dotnet ef --version2) Install required NuGet packages (EF Core + MySQL)
Recommended provider: Pomelo.EntityFrameworkCore.MySql
As of writing this document (2026-02-27)
the current stable Pomelo.EntityFrameworkCore.MySql package (9.0.0)
requires Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.Design packages in version 9.0.13.
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Pomelo.EntityFrameworkCore.MySql
Microsoft.EntityFrameworkCore.Designis required for migrations tooling.
3) Add a simple entity + DbContext (default mapping)
Example entity (User.cs)
public class User
{
public int Id { get; set; } // default PK by convention
public string Name { get; set; } = ""; // default string mapping
}DbContext (AppDbContext.cs)
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
public class AppDbContext : DbContext
{
private const string CONNECTION_STRING =
"server=localhost;port=3306;database=yourdb;user=youruser;password=yourpassword";
public DbSet<User> Users { get; set; }; // DbSet for the entity
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseMySql(
CONNECTION_STRING,
ServerVersion.AutoDetect(CONNECTION_STRING))
.LogTo(Console.WriteLine, LogLevel.Information) // 👈 log SQL
.EnableSensitiveDataLogging() // 👈 include parameter values (dev only!)
.EnableDetailedErrors();
}Default conventions (no attributes/fluent mapping yet):
Idor<TypeName>Idbecomes the primary key- Table name commonly matches the
DbSetname (e.g.,Users)
4) Create your first migration
From the project directory (the one containing the .csproj):
dotnet ef migrations add InitialCreateUseful flags:
# if your startup project differs from the project containing DbContext
dotnet ef migrations add InitialCreate --project ./DataProject --startup-project ./ConsoleProject5) Apply migrations to the database
dotnet ef database update6) Handy EF CLI commands
dotnet ef dbcontext info
dotnet ef dbcontext list
dotnet ef migrations list
dotnet ef migrations remove # removes last migration (if not applied)
dotnet ef database drop -f # drops database (DANGEROUS)7) Use the context in the app
using var dbContext = new AppDbContext();
List<string> userNames = dbContext
.Users
.Select(u => u.Name)
.ToList();