16 KiB
迁移脚本管理
**本文档引用的文件** - [SingleDbMigrationEventHandler.cs](file://aspnet-core/migrations/LY.MicroService.Applications.Single.EntityFrameworkCore/SingleDbMigrationEventHandler.cs) - [SingleDbMigrationService.cs](file://aspnet-core/migrations/LY.MicroService.Applications.Single.EntityFrameworkCore/SingleDbMigrationService.cs) - [SingleMigrationsDbContextFactory.cs](file://aspnet-core/migrations/LY.MicroService.Applications.Single.EntityFrameworkCore.SqlServer/SingleMigrationsDbContextFactory.cs) - [appsettings.json](file://aspnet-core/migrations/LY.MicroService.Applications.Single.DbMigrator/appsettings.json) - [Migrate.ps1](file://aspnet-core/migrations/Migrate.ps1) - [SingleMigrationsEntityFrameworkCoreModule.cs](file://aspnet-core/migrations/LY.MicroService.Applications.Single.EntityFrameworkCore/SingleMigrationsEntityFrameworkCoreModule.cs) - [20231012032107_Initial-Single-Project.cs](file://aspnet-core/migrations/LY.MicroService.Applications.Single.EntityFrameworkCore.MySql/Migrations/20231012032107_Initial-Single-Project.cs) - [20231012032107_Initial-Single-Project.Designer.cs](file://aspnet-core/migrations/LY.MicroService.Applications.Single.EntityFrameworkCore.MySql/Migrations/20231012032107_Initial-Single-Project.Designer.cs)目录
简介
本文档详细介绍了基于Entity Framework Core的迁移脚本管理系统。该系统提供了完整的数据库变更管理解决方案,支持多种数据库(MySQL、PostgreSQL、SQL Server),并通过工厂模式实现了多数据库迁移的统一管理。系统包含迁移事件处理器、迁移服务、配置管理和自动化脚本等功能模块,为企业级应用提供了可靠的数据库版本控制和部署能力。
项目结构
迁移脚本管理系统采用分层架构设计,主要包含以下核心目录结构:
graph TB
subgraph "迁移脚本管理架构"
A[migrations/] --> B[LY.MicroService.Applications.Single.DbMigrator]
A --> C[LY.MicroService.Applications.Single.EntityFrameworkCore]
A --> D[LY.MicroService.Applications.Single.EntityFrameworkCore.MySql]
A --> E[LY.MicroService.Applications.Single.EntityFrameworkCore.PostgreSql]
A --> F[LY.MicroService.Applications.Single.EntityFrameworkCore.SqlServer]
G[LY.MicroService.AuthServer.DbMigrator] --> H[AuthServerMigrations]
I[LY.MicroService.BackendAdmin.DbMigrator] --> J[BackendAdminMigrations]
K[LY.MicroService.Platform.DbMigrator] --> L[PlatformMigrations]
M[Migrate.ps1] --> N[自动化迁移脚本]
O[单体迁移模块] --> P[多数据库支持]
end
图表来源
- Migrate.ps1
- SingleMigrationsEntityFrameworkCoreModule.cs
章节来源
- Migrate.ps1
核心组件
单体迁移上下文(SingleMigrationsDbContext)
单体迁移上下文是整个迁移系统的核心,它集成了多个微服务模块的实体框架配置:
// 核心依赖模块配置
[DependsOn(
typeof(AbpSaasEntityFrameworkCoreModule),
typeof(AbpAuditLoggingEntityFrameworkCoreModule),
typeof(AbpSettingManagementEntityFrameworkCoreModule),
typeof(AbpPermissionManagementEntityFrameworkCoreModule),
typeof(AbpFeatureManagementEntityFrameworkCoreModule),
typeof(AbpNotificationsEntityFrameworkCoreModule),
typeof(AbpMessageServiceEntityFrameworkCoreModule),
typeof(PlatformEntityFrameworkCoreModule),
typeof(AbpLocalizationManagementEntityFrameworkCoreModule),
typeof(AbpIdentityEntityFrameworkCoreModule),
typeof(AbpOpenIddictEntityFrameworkCoreModule),
typeof(AbpTextTemplatingEntityFrameworkCoreModule),
typeof(WebhooksManagementEntityFrameworkCoreModule),
typeof(TaskManagementEntityFrameworkCoreModule),
typeof(AbpGdprEntityFrameworkCoreModule),
typeof(AbpWeChatModule),
typeof(AbpDataDbMigratorModule)
)]
工厂模式支持多数据库
系统通过工厂模式实现了对多种数据库的支持:
classDiagram
class IDesignTimeDbContextFactory {
<<interface>>
+CreateDbContext(args) SingleMigrationsDbContext
}
class SingleMigrationsDbContextFactory {
+CreateDbContext(args) SingleMigrationsDbContext
-BuildConfiguration() IConfigurationRoot
}
class MySqlConnectionFactory {
+CreateDbContext(args) SingleMigrationsDbContext
}
class PostgreSQLConnectionFactory {
+CreateDbContext(args) SingleMigrationsDbContext
}
class SqlServerConnectionFactory {
+CreateDbContext(args) SingleMigrationsDbContext
}
IDesignTimeDbContextFactory <|.. SingleMigrationsDbContextFactory
SingleMigrationsDbContextFactory <|-- MySqlConnectionFactory
SingleMigrationsDbContextFactory <|-- PostgreSQLConnectionFactory
SingleMigrationsDbContextFactory <|-- SqlServerConnectionFactory
图表来源
- SingleMigrationsDbContextFactory.cs
章节来源
- SingleMigrationsEntityFrameworkCoreModule.cs
- SingleMigrationsDbContextFactory.cs
架构概览
迁移脚本管理系统采用事件驱动的架构模式,通过分布式事件总线实现租户级别的数据库迁移管理:
sequenceDiagram
participant CLI as 命令行工具
participant PS as PowerShell脚本
participant Factory as DbContext工厂
participant Service as 迁移服务
participant Handler as 事件处理器
participant DB as 数据库
CLI->>PS : 执行迁移命令
PS->>PS : 选择数据库上下文
PS->>Factory : 创建DbContext实例
Factory->>Factory : 配置连接字符串
Factory->>Service : 初始化迁移服务
Service->>Service : 检查待迁移列表
Service->>Handler : 触发迁移事件
Handler->>DB : 执行数据库迁移
Handler->>Handler : 处理租户数据种子
Handler->>DB : 发布迁移完成事件
DB-->>CLI : 返回迁移结果
图表来源
- Migrate.ps1
- SingleDbMigrationService.cs
详细组件分析
迁移事件处理器(DbMigrationEventHandler)
迁移事件处理器是系统的核心组件之一,负责在数据库迁移过程中执行自定义业务逻辑:
classDiagram
class SingleDbMigrationEventHandler {
-AbpBackgroundTasksOptions Options
-IJobStore JobStore
-IJobScheduler JobScheduler
-IGuidGenerator GuidGenerator
-IdentityUserManager IdentityUserManager
-IdentityRoleManager IdentityRoleManager
-IPermissionDataSeeder PermissionDataSeeder
+HandleEventAsync(eventData) Task
+AfterTenantCreated(eventData, schemaMigrated) Task
#QueueBackgroundJobAsync(eventData) Task
#BuildPollingJobInfo(tenantId, tenantName) JobInfo
#BuildCleaningJobInfo(tenantId, tenantName) JobInfo
#BuildCheckingJobInfo(tenantId, tenantName) JobInfo
#SeedTenantDefaultRoleAsync(eventData) Task
#SeedTenantAdminAsync(eventData) Task
}
class EfCoreDatabaseMigrationEventHandlerBase {
<<abstract>>
+ConnectionStringNameAttribute
+ICurrentTenant CurrentTenant
+IUnitOfWorkManager UnitOfWorkManager
+ITenantStore TenantStore
+IAbpDistributedLock AbpDistributedLock
+IDistributedEventBus DistributedEventBus
+ILoggerFactory LoggerFactory
}
class IDistributedEventHandler {
<<interface>>
+HandleEventAsync(eventData) Task
}
class EntityDeletedEto {
+Entity TenantEto
}
EfCoreDatabaseMigrationEventHandlerBase <|-- SingleDbMigrationEventHandler
IDistributedEventHandler <|.. SingleDbMigrationEventHandler
SingleDbMigrationEventHandler --> EntityDeletedEto
图表来源
- SingleDbMigrationEventHandler.cs
事件处理流程
迁移事件处理器通过监听分布式事件实现租户生命周期管理:
flowchart TD
A[租户创建事件] --> B{检查迁移状态}
B --> |需要迁移| C[队列后台任务]
B --> |无需迁移| D[直接种子数据]
C --> E[构建轮询作业]
C --> F[构建清理作业]
C --> G[构建检查作业]
E --> H[存储作业信息]
F --> H
G --> H
H --> I[调度作业执行]
I --> J[种子租户默认角色]
I --> K[种子租户管理员]
D --> J
J --> L[发布迁移完成事件]
K --> L
图表来源
- SingleDbMigrationEventHandler.cs
迁移服务(DbMigrationService)
迁移服务负责协调数据库迁移过程,确保在多租户环境下正确执行迁移操作:
classDiagram
class SingleDbMigrationService {
-IDataSeeder DataSeeder
-ITenantRepository TenantRepository
+LockAndApplyDatabaseMigrationsAsync() Task
+SeedAsync() Task
}
class EfCoreRuntimeDatabaseMigratorBase {
<<abstract>>
#DatabaseName string
#UnitOfWorkManager IUnitOfWorkManager
#ServiceProvider IServiceProvider
#CurrentTenant ICurrentTenant
#AbpDistributedLock IAbpDistributedLock
#DistributedEventBus IDistributedEventBus
#LoggerFactory ILoggerFactory
}
class ITransientDependency {
<<interface>>
}
EfCoreRuntimeDatabaseMigratorBase <|-- SingleDbMigrationService
ITransientDependency <|.. SingleDbMigrationService
图表来源
- SingleDbMigrationService.cs
分布式锁机制
系统使用分布式锁确保在高并发环境下的迁移安全性:
// 分布式锁获取示例
await using (var handle = await DistributedLock.TryAcquireAsync("DatabaseMigration_" + DatabaseName + "_Tenant" + tenant.Id.ToString()))
{
if (handle is null)
{
Logger.LogInformation($"Distributed lock could not be acquired for database migration: {DatabaseName} with tenant: {tenant.Name}. Operation cancelled.");
return;
}
Logger.LogInformation($"Distributed lock is acquired for database migration: {DatabaseName} with tenant: {tenant.Name}...");
// 执行迁移逻辑
using (CurrentTenant.Change(tenant.Id))
{
// 创建数据库表
using var uow = UnitOfWorkManager.Begin(requiresNew: true, isTransactional: false);
var dbContext = await ServiceProvider.GetRequiredService<IDbContextProvider<SingleMigrationsDbContext>>().GetDbContextAsync();
var pendingMigrations = await dbContext.Database.GetPendingMigrationsAsync();
if (pendingMigrations.Any())
{
await dbContext.Database.MigrateAsync();
schemaMigrated = true;
}
await uow.CompleteAsync();
await SeedAsync();
}
}
章节来源
- SingleDbMigrationEventHandler.cs
- SingleDbMigrationService.cs
自动化迁移脚本
系统提供了PowerShell自动化脚本,简化了迁移操作的复杂性:
flowchart TD
A[启动迁移脚本] --> B[设置环境变量]
B --> C[解析项目路径]
C --> D[显示上下文选择菜单]
D --> E[用户选择数据库上下文]
E --> F[获取迁移名称]
F --> G[执行EF Core迁移命令]
G --> H{是否生成SQL脚本?}
H --> |是| I[选择起始迁移]
H --> |否| J[迁移完成]
I --> K[生成SQL脚本]
K --> L[保存到指定目录]
L --> J
J --> M[显示完成消息]
图表来源
- Migrate.ps1
脚本功能特性
自动化脚本提供了以下核心功能:
- 多数据库上下文支持:支持MySQL、PostgreSQL、SQL Server三种数据库
- 交互式选择界面:提供友好的用户交互体验
- SQL脚本生成:可选择生成全量或增量SQL脚本
- 错误处理:完善的异常捕获和错误提示机制
章节来源
- Migrate.ps1
依赖关系分析
迁移脚本管理系统的依赖关系呈现清晰的层次结构:
graph TB
subgraph "应用层"
A[DbMigratorHostedService] --> B[DbMigrationService]
B --> C[MigrationEventHandler]
end
subgraph "基础设施层"
D[DbContextFactory] --> E[DbContext]
E --> F[EntityFrameworkCore]
G[Configuration] --> D
end
subgraph "领域层"
H[MigrationModule] --> I[EntityFrameworkCoreModule]
I --> F
J[MultiTenancy] --> C
K[DistributedEventBus] --> C
end
subgraph "外部依赖"
L[AbpFramework] --> H
M[EntityFrameworkCore] --> F
N[DatabaseProviders] --> D
end
B --> D
C --> K
E --> J
图表来源
- SingleMigrationsEntityFrameworkCoreModule.cs
章节来源
- SingleMigrationsEntityFrameworkCoreModule.cs
性能考虑
迁移性能优化策略
- 批量操作:通过单元工作模式减少数据库连接开销
- 分布式锁:避免并发迁移导致的数据不一致问题
- 异步处理:使用异步方法提高系统响应性
- 缓存机制:缓存迁移历史记录减少重复查询
内存管理
系统采用以下策略优化内存使用:
- 及时释放数据库连接资源
- 使用流式处理大文件
- 合理设置连接池大小
并发控制
通过分布式锁机制确保:
- 多实例环境下的数据一致性
- 防止重复迁移操作
- 支持高可用部署场景
故障排除指南
常见问题及解决方案
1. 迁移失败问题
症状:迁移过程中出现异常中断 原因:可能是数据库连接问题或权限不足 解决方案:
# 检查数据库连接
dotnet ef database update --project migrations/LY.MicroService.Applications.Single.EntityFrameworkCore.MySql
# 检查迁移历史
dotnet ef migrations list --project migrations/LY.MicroService.Applications.Single.EntityFrameworkCore.MySql
2. SQL脚本生成问题
症状:生成的SQL脚本不完整或语法错误 原因:可能是迁移文件损坏或配置错误 解决方案:
# 清理并重新生成迁移
Remove-Item -Recurse -Force migrations\LY.MicroService.Applications.Single.EntityFrameworkCore.MySql\Migrations
dotnet ef migrations add InitialCreate --project migrations/LY.MicroService.Applications.Single.EntityFrameworkCore.MySql
3. 租户迁移问题
症状:租户数据迁移失败 原因:可能是租户配置或权限问题 解决方案:
- 检查租户表是否存在
- 验证租户权限配置
- 查看迁移日志详情
章节来源
- SingleDbMigrationService.cs
结论
迁移脚本管理系统是一个功能完善、架构清晰的企业级解决方案。它通过以下特点为企业提供了可靠的数据库版本控制能力:
- 多数据库支持:通过工厂模式实现了对MySQL、PostgreSQL、SQL Server的统一支持
- 事件驱动架构:利用分布式事件总线实现租户级别的精细化管理
- 自动化程度高:提供完整的PowerShell脚本自动化迁移流程
- 安全性保障:通过分布式锁和事务机制确保数据一致性
- 扩展性强:模块化设计便于功能扩展和维护
该系统特别适用于微服务架构下的数据库版本管理需求,能够有效支持企业级应用的持续集成和部署流程。通过合理的配置和使用,可以显著提升数据库变更管理的效率和可靠性。