.NET 8+EF Core 8连接MySQL添加迁移时DbContext创建失败求助
我在连接XAMPP的MySQL服务器的ASP.NET Core应用(.NET 8 + EF Core 8)中尝试添加迁移时遇到以下错误:
Unable to create a 'DbContext' of type ''. The exception 'Method not found: 'Void CoreTypeMappingParameters..ctor(System.Type, Microsoft.EntityFrameworkCore.Storage.ValueConversion.ValueConverter, Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer, Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer, Microsoft.EntityFrameworkCore.ChangeTracking.ValueComparer, System.Func`3<Microsoft.EntityFrameworkCore.Metadata.IProperty,Microsoft.EntityFrameworkCore.Metadata.IEntityType,Microsoft.EntityFrameworkCore.ValueGeneration.ValueGenerator>)'.' was thrown while attempting to create an instance.
相关代码
连接配置
// appsettings.json 中的数据库连接字符串 "dbcs": "Server=localhost;Port=3307;Database=asp1;user=root;password=;"
// Program.cs 中的DbContext注入代码 var connectionString = builder.Configuration.GetConnectionString("dbcs"); builder.Services.AddDbContext<StudentDbContext>(item => { item.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)); }); var app = builder.Build();
DbContext代码
using Microsoft.EntityFrameworkCore; namespace WebApplication2.Models { public class StudentDbContext:DbContext { public StudentDbContext(DbContextOptions op) : base(op) { } public DbSet<StudentModel> Students { get; set; } } }
模型类代码
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace WebApplication2.Models { public class StudentModel { [Key] public int Id { get; set; } [Required(ErrorMessage = "Fill the name")] [Column("Student Name", TypeName="varchar(20)")] public string Name { get; set; } public int Age { get; set; } public string Gender { get; set; } } }
解决方法
这个错误核心原因是EF Core 与 MySQL 提供程序版本不兼容,按以下步骤处理:
统一MySQL EF Core包版本
打开NuGet包管理器,将MySql.EntityFrameworkCore的版本更新为8.0.x系列(与EF Core 8版本完全匹配),也可以用CLI命令:dotnet add package MySql.EntityFrameworkCore --version 8.0.33修正DbContext构造函数
将DbContext的构造函数参数改为泛型版本,避免类型匹配问题:public StudentDbContext(DbContextOptions<StudentDbContext> op) : base(op) { }清理重建项目并重试迁移
执行命令清理缓存并重新生成:dotnet clean dotnet restore dotnet ef migrations add InitialCreate检查设计工具版本
确保Microsoft.EntityFrameworkCore.Design包的版本也是8.0.x,与其他EF Core组件版本保持一致。
内容的提问来源于stack exchange,提问作者SAFIQUL ISLAM UZZAL 203-15-144

