数据库迁移问题
第一步,我们选中有DbContext
的项目,然后执行迁移命令:Add-Migration
orUpdate-DataBase
。你会看到控制台报这样的错误:
Your startup project 'FileService.Infrastructure' doesn't reference Microsoft.EntityFrameworkCore.Design. This package is required for the Entity Framework Core Tools to work. Ensure your startup project is correct, install the package, and try again.
第二步,我们就按照报错的提示,给该项目添加Microsoft.EntityFrameworkCore.Design
依赖包。然后再执行迁移命令,你会看到下面这样的报错信息:
你可以自己通过后面那个提示链接去查看解决方案,或者按照下面这种方案。
第三步,添加对项目的引用:
第四步,在当前项目下添加一个继承于IDesignTimeDbContextFactory
的类,代码如下:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<FSDbContext>
{
public FSDbContext CreateDbContext(string[] args)
{
var optionsBuilder = DbContextOptionsBuilderFactory.Create<FSDbContext>();
return new FSDbContext(optionsBuilder.Options, null);
}
}
上述代码是根据项目代码结构进行的改写,可以根据自己的需求将代码改编。
第四步,执行数据迁移命令,成功。