EF Core怎么连接MySQL数据库 EF Core连接MySQL方法

来源:这里教程网 时间:2026-02-21 17:36:14 作者:

EF Core 连接 MySQL 数据库,核心就三步:装对驱动、配好连接字符串、注册 DbContext。用 Pomelo 提供程序是当前最主流、兼容性最好、文档最全的选择(官方 MySQL EF 包已基本停止维护)。

安装 Pomelo 驱动和基础包

在项目中执行以下命令(.NET 6/7/8/9 均适用):

dotnet add package Pomelo.EntityFrameworkCore.MySql —— 必装,MySQL 的 EF Core 提供程序 dotnet add package Microsoft.EntityFrameworkCore.Design —— 支持迁移命令(
dotnet ef
dotnet add package Microsoft.EntityFrameworkCore.Tools —— 设计时工具(VS 中的包管理器控制台也依赖它)

不需要再装

MySql.Data
MySql.Data.EntityFrameworkCore
,Pomelo 已内置完整实现,且更活跃、适配新版 MySQL(如 8.0+ 的 caching_sha2_password 认证)。

配置连接字符串(推荐 appsettings.json)

appsettings.json
ConnectionStrings
节点下添加:

"ConnectionStrings": {
  "MySqlDb": "server=localhost;port=3306;database=myappdb;user=root;password=123456;CharSet=utf8mb4;"
}

关键细节:

utf8mb4
替代
utf8
:支持 emoji 和四字节 Unicode 字符
显式写
port=3306
:避免默认端口误判;若改过端口(如腾讯云/阿里云 RDS),务必填对
密码含特殊字符(如
@
/
)时,需 URL 编码(例如
pass@123
pass%40123

定义 DbContext 并注册服务

新建上下文类,比如

AppDbContext.cs

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
    public DbSet<User> Users { get; set; }
}

Program.cs
(.NET 6+)中注册:

var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("MySqlDb");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));

注意:

ServerVersion.AutoDetect
会自动识别 MySQL 版本(5.7 / 8.0 / 8.4),无需手动指定;如需精确控制(如用 8.0.33 的特性),可改为
new ServerVersion(new Version(8, 0, 33), ServerType.MySql)

生成数据库表(Code First)

实体类写好后,运行两条命令即可建库建表:

dotnet ef migrations add InitialCreate dotnet ef database update

首次运行会自动创建数据库(只要连接字符串里指定的库名不存在,Pomelo 默认会尝试创建);若提示权限不足,请确认 MySQL 用户有

CREATE DATABASE
权限。

基本上就这些。不复杂但容易忽略的是字符集、端口、认证方式这三点——连不上时优先检查它们。

相关推荐

热文推荐