Blazor WebAssembly连接MySQL Workbench报错:连接字符串无效问题
Blazor连接MySQL的正确配置与错误修复
核心错误原因
你遇到的SqlException是因为代码默认使用了SQL Server的EF Core驱动,但你实际要连接的是MySQL,同时连接字符串也是SQL Server格式,导致程序试图连接错误的数据库类型。
1. 安装MySQL专属EF Core驱动
卸载可能存在的SQL Server驱动(Microsoft.EntityFrameworkCore.SqlServer),安装MySQL官方推荐的EF Core provider:
Install-Package Pomelo.EntityFrameworkCore.MySql Install-Package Microsoft.EntityFrameworkCore.Tools
2. 修正AppDbContext代码
确保你的上下文类仅依赖通用EF Core接口,不要绑定SQL Server:
using Microsoft.EntityFrameworkCore; public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } // 在此定义你的实体集合,例如: // public DbSet<Product> Products { get; set; } }
3. 配置Startup.cs(.NET 5及更早)或Program.cs(.NET 6+)
.NET 5 Startup.cs 配置
using Microsoft.EntityFrameworkCore; public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) => Configuration = configuration; public void ConfigureServices(IServiceCollection services) { // 替换SQL Server配置为MySQL services.AddDbContext<AppDbContext>(options => options.UseMySql( Configuration.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(Configuration.GetConnectionString("DefaultConnection")) ) ); services.AddRazorPages(); services.AddServerSideBlazor(); // 其他服务配置 } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 中间件配置(按你的需求保留) } }
.NET 6+ Program.cs 配置
using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // 添加MySQL上下文服务 builder.Services.AddDbContext<AppDbContext>(options => options.UseMySql( builder.Configuration.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("DefaultConnection")) ) ); builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); var app = builder.Build(); // 中间件配置(按你的需求保留) app.Run();
4. 修正连接字符串(appsettings.json)
使用MySQL格式的连接字符串,与你MySQL Workbench中的连接参数完全一致:
{ "ConnectionStrings": { "DefaultConnection": "server=你的服务器地址;port=3306;database=目标数据库名;user=数据库用户名;password=数据库密码;charset=utf8mb4" } }
注意:不要使用包含
Data Source、Initial Catalog的SQL Server格式连接字符串,这是导致你报错的直接原因。
5. 验证与测试
- 确认MySQL服务正在运行
- 执行EF Core迁移(如果需要):
Add-Migration InitialCreate Update-Database
- 启动Blazor应用,测试数据库操作
内容的提问来源于stack exchange,提问作者Asel Dev
相关产品推荐
相关产品推荐

