首先来一段错误
immodeMacBook-Pro:tz.efcontext immo$ dotnet ef database update
Unable to create an object of type 'AppDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<AppDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time
上面有提示中有两个解决方案
一个是“IDesignTimeDbContextFactory”
一个是后面的地址
地址里面有两个解决方案
一个是无参构造函数
另外一个就是上面那个【有点废话】
无参玩失败了,只能走下面的“IDesignTimeDbContextFactory”
实现代码可以看ef扩展的mysql类库“Pomelo.EntityFrameworkCore.MySql” ,在搭建环境的时候肯定会用到
点击打开链接https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql
实现代码【最终版】
using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
namespace tz.efcontext
{
public class DesignTimeDbContextFactory: IDesignTimeDbContextFactory<AppDbContext>
{
public AppDbContext CreateDbContext(string[] args)
{
//下面是官方代码,但是由于我是自己新建的类库,不是web项目,所以点不出 SetBasePath 来,可以自己想办法读取到web项目的配置文件里面的配
//IConfigurationRoot configuration = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile("appsettings.json")
// .Build();
//var connectionString = configuration.GetConnectionString("AppSqlConnection");
//数据库连接字符串
var connectionString = "Server=oauth.zhouquan.wang;database=xxhbg;uid=dba_xxhbg;pwd=dba_6462xxhbg;Character Set=utf8;persist security info=True";
var builder = new DbContextOptionsBuilder<AppDbContext>();
builder.UseMySql(connectionString,
mysqlOptions =>
{
//迁移的时候,会报sql语法错误,迁移sql脚本应该是按照最新的api生成的,在旧版本数据库中不兼
mysqlOptions.ServerVersion(new Version(5, 0, 96), ServerType.MySql);
}
);
return new AppDbContext(builder.Options);
}
}
}
注意看里面的注释
遇到的其他问题
1.“DesignTimeDbContextFactory”类的示例是放在表示层,我要移植到“DbContext”同一层
2.移植过后“ConfigurationBuilder”无法点出“SetBasePath”方法,猜测是web层的引用扩渣的(这里我先不读取配置文件,直接写死连接字符串了
3.配置过后成功的生成了迁移文件,如下图;但是在更新数据库的时候失败了,大概是报了sql语法错误,原因是我的mysql的版本是5.x.x,生成的sql语句应该是最新版本(猜测),在github找到“Pomelo.EntityFrameworkCore.MySql”文档,发现了一个很好的配置,就是数据库版本
mysqlOptions.ServerVersion(new Version(5, 0, 96), ServerType.MySql); //不用看这里,上面有完整的
最后附上我的
##初始化
dotnet ef migrations add [<The name of the migration>] -s ../tz.web
dotnet ef migrations add zq1 -s ../tz.web
##更新数据库
dotnet ef database update -s ../tz.web
其中 [../tz.web]应该是../tz.web “startup项目的位置”,需要DesignTimeDbContextFactory来创建dbcontext
假设你的DesignTimeDbContextFactory在web层,DbContext在其他层,那么就需要上面的-s,如果不是则省略-s
执行命令需要前往DbContext层执行哦