由于笔者写此文时.net core 2.1 对mysql 8.0.11的相关版本支持还不够完善,因此需要做以下改动
我们使用Pomelo.EntityFrameworkCore.MySql作为mysql efcore的支持类库
一、编辑项目csproj文件,配置引用包的版本(这点很重要,否则在Add-Migration迁移的时候就会报错)
参考地址:https://stackoverflow.com/questions/50650463/specifically-target-older-version-of-single-net-standard-api-namespace-entity/50652838#50652838
错误提示:Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.Internal.RelationalParameterBuilder..ctor(Microsoft.EntityFrameworkCore.Storage.IRelationalTypeMapper)'.
修改配置如下:Microsoft.EntityFrameworkCore设置为2.0.3,Pomelo.EntityFrameworkCore.MySql设置为2.0.1
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.3" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.1" />
</ItemGroup>
保存之后,项目根目录执行命令dotnet restore
二、在和数据库上下文同一目录新建类DesignTimeDbContextFactory
参考地址:https://stackoverflow.com/questions/45782446/unable-to-create-migrations-after-upgrading-to-asp-net-core-2-0?answertab=active#tab-top
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<UserContext>
{
public UserContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<UserContext>();
var connectionString = configuration.GetConnectionString("MysqlUser");
builder.UseMySql(connectionString);
return new UserContext(builder.Options);
}
}
配置完这两处之后重新构建
我们就可以使用
Add-Migration Init
Update-DataBase
这两个命令时时同步构建Mysql数据库了。
项目地址:https://github.com/quezhihui/MySQLWebApi