.Net Core 3.x项目切MySQL8运行Migrator报datetime2未知类型错误
错误根因
该错误是因为之前适配MSSQL生成的迁移文件中使用了SQL Server独有的datetime2数据类型,MySQL不支持该类型;同时你使用的Pomelo.EntityFrameworkCore.MySql 3.2.7版本未显式指定MySQL版本时,类型映射逻辑会出现偏差,也可能触发该错误。
解决步骤
1. 清理旧迁移文件
删除项目Migrations目录下所有基于MSSQL生成的历史迁移文件,避免旧的datetime2配置残留。
2. 显式指定MySQL版本
修改DBContextConfigurer类的配置代码,传入你使用的MySQL 8.0.27版本信息:
public static void Configure(DbContextOptionsBuilder<LandAndBnbDbContext> builder, string connectionString) { builder.UseMySql(connectionString, new MySqlServerVersion(new Version(8, 0, 27))); } public static void Configure(DbContextOptionsBuilder<LandAndBnbDbContext> builder, DbConnection connection) { builder.UseMySql(connection, new MySqlServerVersion(new Version(8, 0, 27))); }
3. 全局配置DateTime类型映射(可选)
如果你的项目对时间精度有要求,可在DbContext的OnModelCreating方法中全局配置DateTime类型适配MySQL规则:
protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // 全局将所有DateTime属性映射为MySQL的datetime(6)类型 modelBuilder.Properties<DateTime>() .Configure(p => p.HasColumnType("datetime(6)")); }
4. 重新生成并执行迁移
使用包管理器控制台执行以下命令:
- 生成适配MySQL的新迁移文件:
Add-Migration InitMySql - 执行迁移更新数据库:
Update-Database
如果使用dotnet CLI,对应命令为:
dotnet ef migrations add InitMySqldotnet ef database update
5. 验证迁移
重新运行Migrator项目即可正常完成数据库迁移。
内容的提问来源于stack exchange,提问作者Vassilis Ntigrintakis
相关产品推荐
相关产品推荐

