var serviceProvider = services.BuildServiceProvider();[/mw_shl_code]
EF Core有属于它自己的容器,所以我们将全局容器和上下文所属容器做了区分,同时呢,我们将迁移中要用到的操作依赖也手动添加,比如上面的设计服务,存在于 Microsoft.EntityFrameworkCore.Design 包内,最后将获取数据库表结构模型工厂手动注入即MySqlDatabaseModelFactory。接下来我们要获取模型定义以及属性一些定义等等,也就是我们最终要生成的目标模型结构
using var scope = _serviceProvider.CreateScope();
var currentServiceProvider = scope.ServiceProvider;
var context = (DbContext)currentServiceProvider.GetRequiredService<T>();
var connectionString = context.Database.GetDbConnection().ConnectionString;
var targetModel = context.GetService<IDesignTimeModel>().Model.GetRelationalModel();
if (targetModel == null)
{
return Enumerable.Empty<MigrationOperation>().ToList();
}
接下来则是获取数据库表结构也就是数据库模型
var databaseFactory = currentServiceProvider.GetService<IDatabaseModelFactory>();
var factory = currentServiceProvider.GetService<IScaffoldingModelFactory>();
var tables = context.Model.GetEntityTypes().Select(e => e.GetTableName()).ToList();
if (!tables.Any())
{
return Enumerable.Empty<MigrationOperation>().ToList();
}
// 仅查询当前上下文模型所映射表,否则比对数据库表差异时,将会删除非当前上下文所有表
var databaseModel = databaseFactory.Create(connectionString, new DatabaseModelFactoryOptions(tables: tables));
if (databaseModel == null)
{
return Enumerable.Empty<MigrationOperation>().ToList();
}