You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行EF Core迁移时遇DbContext创建失败及MariaDB连接问题求助

问题解决步骤

1. 修正数据库服务注册(program.cs)

当前代码错误地注册了SqlServer的DbContext,需改为MySQL适配的配置,同时移除无用的SqlClient引用:

using fixit.Data;
using fixit.Models;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// 修正:替换为MySQL的DbContext配置
builder.Services.AddDbContext<DataContext>(opt => 
    opt.UseMySql(builder.Configuration.GetConnectionString("WebApiDatabase"), 
        ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("WebApiDatabase"))));

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddCors(option =>
            {
                option.AddPolicy("allowedOrigin",
                    builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
                    );
            });
builder.Services.AddControllers();
builder.Services.AddScoped<IRepository<Service>, ServiceRepository>();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// 后续管道配置保持不变
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseCors(builder => builder
       .AllowAnyHeader()
       .AllowAnyMethod()
       .AllowAnyOrigin()
    );
app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
});

app.Run();

2. 精简DataContext构造函数

多个构造函数会导致EF Core设计时无法正确实例化DbContext,保留带DbContextOptions的构造即可:

using fixit.Models;
using Microsoft.EntityFrameworkCore;

namespace fixit.Data
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> options) : base(options) { }

        public DbSet<Service> Service { get; set; }
    }
}

3. 修正连接字符串(appsettings.json)

移除密码字段后的多余空格,若root有实际密码则补充完整:

{
  "ConnectionStrings": {
    "WebApiDatabase": "server=localhost; database=test; user=root; password=;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

4. 解决MySQL/MariaDB主机权限问题

错误提示主机无法连接,需给root用户授权localhost访问权限:

  1. 登录MySQL命令行:
mysql -u root -p
  1. 执行授权命令(替换你的密码为实际root密码):
GRANT ALL PRIVILEGES ON test.* TO 'root'@'localhost' IDENTIFIED BY '你的密码';
FLUSH PRIVILEGES;

若使用127.0.0.1连接,需额外授权root@'127.0.0.1'。

5. 重新执行迁移

确保安装了MySQL的EF Core驱动,未安装则先执行:

dotnet add package Pomelo.EntityFrameworkCore.MySql

然后重新运行迁移命令:

dotnet ef migrations add InitialCreate
dotnet ef database update

内容的提问来源于stack exchange,提问作者user21497668

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:32:29