


增加一个MySQL的库:Volo.Abp.EntityFrameworkCore.MySQL
<PackageReference Include="Volo.Abp.EntityFrameworkCore.MySQL" Version="4.4.2" />
然后把UseSqlServer换成UseMySQL
在把上下文对象中的连接字符串修改以下
以为这种就行了?那太天真了
执行迁移命令马上报错:Unable to create an object of type ‘DbContext’. For the different patterns supported at design time。
连接MySQL需要自己重写以下IDesignTimeDbContextFactory接口,配置一点逻辑
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<WyJBLandDbContext>
{
public WyJBLandDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<WyJBLandDbContext>();
optionsBuilder.UseMySql(ServerVersion.AutoDetect("你的连接字符串"));
return new WyJBLandDbContext(optionsBuilder.Options);
}
}
但是如果只是上边那样,虽然执行Add-Migration InitialCreate不会报错,能够正常生成迁移命令但是执行Update-Database就会报错了。
“A relational store has been configured without specifying either the DbConnection or connection string to use.”
只传递一个参数虽然执行迁移命令不会报错,但是执行Update-Database就会报错了。所以需要调用两个参数的方法。
解决方案
在UseMysql上,要传递两个参数(connectionstring,ServerVersion)
贴一下完整的代码,包括读取配置文件的代码
/* This class is needed for EF Core console commands
* (like Add-Migration and Update-Database commands) */
public class WyJBLandDbContextFactory : IDesignTimeDbContextFactory<WyJBLandDbContext>
{
public WyJBLandDbContext CreateDbContext(string[] args)
{
//BookStoreEfCoreEntityExtensionMappings.Configure();
var configuration = BuildConfiguration();
string conn = configuration.GetConnectionString("conn_mysql");
AddTestLog(conn);
var builder = new DbContextOptionsBuilder<WyJBLandDbContext>()
.UseMySql(conn,ServerVersion.AutoDetect(conn));
return new WyJBLandDbContext(builder.Options);
}
/// <summary>
/// 记录一点内容用于测试连接字符串是否正确获取到
/// </summary>
/// <param name="content"></param>
public void AddTestLog(string content)
{
using (FileStream filestraem = new FileStream("d:/log.txt", FileMode.Append))
{
using (StreamWriter write = new StreamWriter(filestraem))
{
write.WriteLine(content);
write.WriteLine("记录时间:" + DateTime.Now.ToString());
write.WriteLine("----------------------------------------");
write.Flush();
}
}
}
private static IConfigurationRoot BuildConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "../WY.JBLand.API/"))
.AddJsonFile("appsettings.json", optional: true);
return builder.Build();
}
}
还要注意以下mysql连接字符串不能使用.哦,要使用localhost代替否者会报错:
Unable to connect to any of the specified MySQL hosts.
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739。有需要软件开发,或者学习软件技术的朋友可以和我联系~(Q:815170684)