abp vnext连接mysql。.net core连接mysql。ef core连接mysql 电脑版发表于:2022/5/23 11:45 增加一个MySQL的库:Volo.Abp.EntityFrameworkCore.MySQL ``` <PackageReference Include="Volo.Abp.EntityFrameworkCore.MySQL" Version="4.4.2" /> ``` 然后把UseSqlServer换成UseMySQL ![](https://img.tnblog.net/arcimg/aojiancc2/0a27cb0fb73143e9b784baa17f38c53a.png) 在把上下文对象中的连接字符串修改以下 ![](https://img.tnblog.net/arcimg/aojiancc2/4586d838991d4b91a6092191a696437a.png) **以为这种就行了?那太天真了** tn4> 执行迁移命令马上报错: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就会报错了。 tn4>“A relational store has been configured without specifying either the DbConnection or connection string to use.” 只传递一个参数虽然执行迁移命令不会报错,但是执行Update-Database就会报错了。所以需要调用两个参数的方法。 **解决方案** 在UseMysql上,要传递两个参数(connectionstring,ServerVersion) ![](https://img.tnblog.net/arcimg/aojiancc2/1bf090af3b804135bece89282ec9c600.png) 贴一下完整的代码,包括读取配置文件的代码 ``` /* 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(); } } ``` tn6> 还要注意以下mysql连接字符串不能使用.哦,要使用localhost代替否者会报错: Unable to connect to any of the specified MySQL hosts.