报错信息:
Your target project 'ReviewTransactionScope.Api' doesn't match your migrations assembly 'ReviewTransactionScope.Infrastructure'. Either change your target project or change your migrations assembly.
Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("ReviewTransactionScope.Api")). By default, the migrations assembly is the assembly containing the DbContext.
Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.
解释:
你的目标项目’ReviewTransactionScope.Api’与你的迁移程序集’ReviewTransactionScope.Infrastructure’不匹配。你可以更改目标项目或者更改迁移程序集。
使用DbContextOptionsBuilder来更改迁移程序集。例如,你可以使用以下代码:
在program.cs中修改数据库配置项
options.UseSqlServer(connection, b => b.MigrationsAssembly(“ReviewTransactionScope.Api”));
默认情况下,迁移程序集是包含DbContext的程序集。但是你可以通过指定所需的迁移程序集来覆盖默认设置。
请确保根据你的项目结构和需求选择适合的选项。
项目结构
解决:
修改program.cs中的配置
// 注入数据库上下文
builder.Services.AddDbContext<MyDebContext>(opt =>
{
// 获取配置中 的连接字符串
string str = builder.Configuration.GetConnectionString("Default");
// 指定migration的程序集位置
opt.UseSqlServer(str, b => b.MigrationsAssembly("ReviewTransactionScope.Api")
);
});
再次执行:add-migration xx 成功! update-database 成功!