项目中我们希望DbContext支持多种数据库,需要为每一种数据库创建一个迁移文件,具体的办法是,DbContext类库中不引用具体的数据库Provider,为每一种数据库创建独立的迁移类库,引用相关的数据库Provider,比如针对SqlServer,可以创建一个类库,名称为PoemGame.Repositories.EF.SqlServer,引用程序包Microsoft.EntityFrameworkCore.SqlServer和Microsoft.EntityFrameworkCore.Tools,在类库中创建DesignDbContextFactory:
public class GameDbContextFactory : IDesignTimeDbContextFactory<GameDbContext>
{
public GameDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<GameDbContext>();
optionsBuilder.UseSqlServer("Server=.;Database=PoemGameEF;Integrated Security=true",
x => x.MigrationsAssembly("PoemGame.Repositories.EF.SqlServer"));
return new GameDbContext(optionsBuilder.Options);
}
}
在程序包管理器中,选择这个项目作为默认项目,并且将该项目设置为启动项目。运行Add-Migration, 就可以生成迁移文件了。可以创建依赖注入扩展如下:
public static IServiceCollection AddPoemGameEF(this IServiceCollection services, IConfiguration Configuration)
{
services.AddDbContext<GameDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PoemGameConnection"),
x => x.MigrationsAssembly("PoemGame.Repositories.EF.SqlServer")));