Rename projects to FileShare
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
using FileShare_EFCore.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FileShare_EFCore.Database
|
||||
{
|
||||
/// <summary>
|
||||
/// 应用数据库上下文 —— 继承自 FileShare-EFCore 的 AppDbContext。
|
||||
/// 所有业务实体在此注册 DbSet。
|
||||
/// 这是 FileShare-API 和 FileShare-PC 共用的具体数据上下文。
|
||||
/// </summary>
|
||||
public class AppDataContext(DatabaseConfiguration dbConfig) : AppDbContext(dbConfig)
|
||||
{
|
||||
/// <summary>天气预报数据</summary>
|
||||
public DbSet<WeatherForecastEntity> WeatherForecasts => Set<WeatherForecastEntity>();
|
||||
|
||||
/// <summary>用户数据</summary>
|
||||
public DbSet<UserEntity> Users => Set<UserEntity>();
|
||||
|
||||
/// <summary>API refresh token 数据</summary>
|
||||
public DbSet<ApiRefreshTokenEntity> ApiRefreshTokens => Set<ApiRefreshTokenEntity>();
|
||||
|
||||
/// <summary>文件库根目录数据</summary>
|
||||
public DbSet<ManagedLibraryRoot> ManagedLibraryRoots => Set<ManagedLibraryRoot>();
|
||||
|
||||
/// <summary>文件库文件记录数据</summary>
|
||||
public DbSet<ManagedFileRecord> ManagedFileRecords => Set<ManagedFileRecord>();
|
||||
|
||||
/// <summary>
|
||||
/// 配置实体映射,包括主键、索引和属性约束。
|
||||
/// </summary>
|
||||
/// <param name="modelBuilder">模型构建器。</param>
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.Entity<WeatherForecastEntity>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id).HasName("pk-weather-forecast");
|
||||
entity.Property(e => e.Summary).HasMaxLength(200);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<UserEntity>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id).HasName("pk-user");
|
||||
entity.Property(e => e.Email).HasMaxLength(200);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ApiRefreshTokenEntity>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id).HasName("pk-api-refresh-token");
|
||||
entity.HasIndex(e => e.TokenHash).IsUnique().HasDatabaseName("idx-api-refresh-token-hash");
|
||||
entity.HasIndex(e => e.UserId).HasDatabaseName("idx-api-refresh-token-user-id");
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ManagedLibraryRoot>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id).HasName("pk-managed-library-root");
|
||||
entity.HasIndex(e => e.Path).IsUnique().HasDatabaseName("idx-managed-library-root-path");
|
||||
entity.Property(e => e.Path).HasMaxLength(1024);
|
||||
entity.Property(e => e.DisplayName).HasMaxLength(200);
|
||||
entity.Property(e => e.LastScanError).HasMaxLength(2000);
|
||||
entity.Property(e => e.IsAvailable).HasDefaultValue(true);
|
||||
});
|
||||
|
||||
modelBuilder.Entity<ManagedFileRecord>(entity =>
|
||||
{
|
||||
entity.HasKey(e => e.Id).HasName("pk-managed-file-record");
|
||||
entity.HasIndex(e => e.LibraryRootId).HasDatabaseName("idx-managed-file-record-root-id");
|
||||
entity.HasIndex(e => e.AbsolutePath).IsUnique().HasDatabaseName("idx-managed-file-record-absolute-path");
|
||||
entity.HasIndex(e => new { e.MediaType, e.Exists }).HasDatabaseName("idx-managed-file-record-media-type-exists");
|
||||
entity.Property(e => e.FileName).HasMaxLength(260);
|
||||
entity.Property(e => e.RelativePath).HasMaxLength(1024);
|
||||
entity.Property(e => e.AbsolutePath).HasMaxLength(2048);
|
||||
entity.Property(e => e.Extension).HasMaxLength(32);
|
||||
entity.Property(e => e.MediaType).HasMaxLength(20);
|
||||
entity.Property(e => e.ContentType).HasMaxLength(100);
|
||||
entity.HasOne(e => e.LibraryRoot)
|
||||
.WithMany(e => e.Files)
|
||||
.HasForeignKey(e => e.LibraryRootId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
|
||||
namespace FileShare_EFCore.Database
|
||||
{
|
||||
/// <summary>
|
||||
/// 设计时 DbContext 工厂,用于 EF Core 迁移工具生成迁移代码。
|
||||
/// </summary>
|
||||
public class AppDataContextFactory : IDesignTimeDbContextFactory<AppDataContext>
|
||||
{
|
||||
/// <summary>
|
||||
/// 创建用于设计时的 AppDataContext 实例,默认使用 SQLite 提供程序。
|
||||
/// </summary>
|
||||
/// <param name="args">命令行参数。</param>
|
||||
/// <returns>配置好的数据上下文实例。</returns>
|
||||
public AppDataContext CreateDbContext(string[] args)
|
||||
{
|
||||
return new AppDataContext(DesignTimeDatabaseConfiguration.Create(args));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SQLite 迁移设计时工厂。
|
||||
/// </summary>
|
||||
public sealed class SqliteAppDataContextFactory : IDesignTimeDbContextFactory<SqliteAppDataContext>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public SqliteAppDataContext CreateDbContext(string[] args)
|
||||
=> new(DesignTimeDatabaseConfiguration.Create(args, DatabaseProvider.SQLite));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server 迁移设计时工厂。
|
||||
/// </summary>
|
||||
public sealed class SqlServerAppDataContextFactory : IDesignTimeDbContextFactory<SqlServerAppDataContext>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public SqlServerAppDataContext CreateDbContext(string[] args)
|
||||
=> new(DesignTimeDatabaseConfiguration.Create(args, DatabaseProvider.SqlServer));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PostgreSQL 迁移设计时工厂。
|
||||
/// </summary>
|
||||
public sealed class PostgreSqlAppDataContextFactory : IDesignTimeDbContextFactory<PostgreSqlAppDataContext>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public PostgreSqlAppDataContext CreateDbContext(string[] args)
|
||||
=> new(DesignTimeDatabaseConfiguration.Create(args, DatabaseProvider.PostgreSQL));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MySQL 迁移设计时工厂。
|
||||
/// </summary>
|
||||
public sealed class MySqlAppDataContextFactory : IDesignTimeDbContextFactory<MySqlAppDataContext>
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public MySqlAppDataContext CreateDbContext(string[] args)
|
||||
=> new(DesignTimeDatabaseConfiguration.Create(args, DatabaseProvider.MySQL));
|
||||
}
|
||||
|
||||
internal static class DesignTimeDatabaseConfiguration
|
||||
{
|
||||
public static DatabaseConfiguration Create(string[] args, DatabaseProvider defaultProvider = DatabaseProvider.SQLite)
|
||||
{
|
||||
DatabaseProviderRegistry.RegisterDefaults();
|
||||
|
||||
var provider = GetProvider(args) ?? defaultProvider;
|
||||
return provider switch
|
||||
{
|
||||
DatabaseProvider.SQLite => DatabaseConfiguration.ForSQLite("fileshare-api.db"),
|
||||
DatabaseProvider.SqlServer => DatabaseConfiguration.ForSqlServer("(localdb)\\MSSQLLocalDB", "FileShareApi"),
|
||||
DatabaseProvider.PostgreSQL => DatabaseConfiguration.ForPostgreSQL("localhost", "fileshare_api", "postgres", "postgres"),
|
||||
DatabaseProvider.MySQL => DatabaseConfiguration.ForMySQL("localhost", "fileshare_api", "root", "root"),
|
||||
_ => DatabaseConfiguration.ForSQLite("fileshare-api.db"),
|
||||
};
|
||||
}
|
||||
|
||||
private static DatabaseProvider? GetProvider(string[] args)
|
||||
{
|
||||
for (var i = 0; i < args.Length; i++)
|
||||
{
|
||||
var arg = args[i];
|
||||
string? value = null;
|
||||
|
||||
if (arg.Equals("--provider", StringComparison.OrdinalIgnoreCase) && i + 1 < args.Length)
|
||||
{
|
||||
value = args[i + 1];
|
||||
}
|
||||
else if (arg.StartsWith("--provider=", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = arg["--provider=".Length..];
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(value)
|
||||
&& Enum.TryParse<DatabaseProvider>(value, ignoreCase: true, out var provider))
|
||||
{
|
||||
return provider;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FileShare_EFCore.Database
|
||||
{
|
||||
/// <summary>
|
||||
/// 应用数据库上下文基类 —— 自动根据 DatabaseConfiguration 选择数据库提供程序。
|
||||
/// 所有业务 DbContext 继承此类即可获得多数据库支持。
|
||||
/// </summary>
|
||||
public abstract class AppDbContext(DatabaseConfiguration dbConfig) : DbContext
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库配置。
|
||||
/// </summary>
|
||||
private readonly DatabaseConfiguration _dbConfig = dbConfig;
|
||||
|
||||
/// <summary>
|
||||
/// 配置数据库提供程序和连接选项。
|
||||
/// </summary>
|
||||
/// <param name="optionsBuilder">选项构建器。</param>
|
||||
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
|
||||
{
|
||||
if (optionsBuilder.IsConfigured) return;
|
||||
|
||||
ConfigureProvider(optionsBuilder, _dbConfig);
|
||||
|
||||
if (_dbConfig.EnableDetailedLog)
|
||||
{
|
||||
optionsBuilder.LogTo(Console.WriteLine, Microsoft.Extensions.Logging.LogLevel.Information);
|
||||
}
|
||||
|
||||
// 启用详细的 EF Core 错误信息
|
||||
optionsBuilder.EnableDetailedErrors();
|
||||
optionsBuilder.EnableSensitiveDataLogging(_dbConfig.EnableDetailedLog);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据配置选择数据库提供程序。
|
||||
/// 使用注册模式,由宿主项目注册具体的提供程序实现。
|
||||
/// </summary>
|
||||
public static void ConfigureProvider(DbContextOptionsBuilder optionsBuilder, DatabaseConfiguration config)
|
||||
{
|
||||
if (DatabaseProviderRegistry.TryGet(config.Provider, out var configurator))
|
||||
{
|
||||
configurator(optionsBuilder, config.ConnectionString, config.Timeout);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"数据库提供程序 {config.Provider} 未注册。" +
|
||||
$"请在宿主项目中安装对应的 EF Core NuGet 包并调用 DatabaseProviderRegistry.Register()。");
|
||||
}
|
||||
|
||||
optionsBuilder.EnableDetailedErrors();
|
||||
optionsBuilder.EnableSensitiveDataLogging(config.EnableDetailedLog);
|
||||
|
||||
if (config.EnableDetailedLog)
|
||||
{
|
||||
optionsBuilder.LogTo(Console.WriteLine, Microsoft.Extensions.Logging.LogLevel.Information);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存时自动设置时间戳。
|
||||
/// </summary>
|
||||
public override int SaveChanges(bool acceptAllChangesOnSuccess)
|
||||
{
|
||||
SetTimestamps();
|
||||
return base.SaveChanges(acceptAllChangesOnSuccess);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步保存更改,自动设置时间戳。
|
||||
/// </summary>
|
||||
/// <param name="acceptAllChangesOnSuccess">是否在成功时接受所有更改。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
/// <returns>受影响的行数。</returns>
|
||||
public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
|
||||
{
|
||||
SetTimestamps();
|
||||
return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 自动设置新增或修改实体的 CreatedAt 和 UpdatedAt 时间戳。
|
||||
/// </summary>
|
||||
private void SetTimestamps()
|
||||
{
|
||||
var entries = ChangeTracker.Entries()
|
||||
.Where(e => e.State == EntityState.Added || e.State == EntityState.Modified);
|
||||
|
||||
foreach (var entry in entries)
|
||||
{
|
||||
var entity = entry.Entity;
|
||||
|
||||
// 使用反射设置 CreatedAt / UpdatedAt(如果存在)
|
||||
var createdAtProp = entity.GetType().GetProperty("CreatedAt");
|
||||
var updatedAtProp = entity.GetType().GetProperty("UpdatedAt");
|
||||
|
||||
if (entry.State == EntityState.Added && createdAtProp != null)
|
||||
{
|
||||
createdAtProp.SetValue(entity, DateTime.UtcNow);
|
||||
}
|
||||
|
||||
if (updatedAtProp != null)
|
||||
{
|
||||
updatedAtProp.SetValue(entity, DateTime.UtcNow);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
namespace FileShare_EFCore.Database
|
||||
{
|
||||
/// <summary>
|
||||
/// 支持的数据库提供程序类型。
|
||||
/// </summary>
|
||||
public enum DatabaseProvider
|
||||
{
|
||||
/// <summary>SQLite(本地文件数据库,无需安装,跨平台)</summary>
|
||||
SQLite,
|
||||
|
||||
/// <summary>MySQL / MariaDB</summary>
|
||||
MySQL,
|
||||
|
||||
/// <summary>PostgreSQL</summary>
|
||||
PostgreSQL,
|
||||
|
||||
/// <summary>SQL Server</summary>
|
||||
SqlServer
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数据库连接配置 —— 在 appsettings.json 中配置。
|
||||
/// </summary>
|
||||
public class DatabaseConfiguration
|
||||
{
|
||||
/// <summary>数据库提供程序</summary>
|
||||
public DatabaseProvider Provider { get; set; } = DatabaseProvider.SQLite;
|
||||
|
||||
/// <summary>连接字符串</summary>
|
||||
public string ConnectionString { get; set; } = "Data Source=app.db";
|
||||
|
||||
/// <summary>是否在启动时自动执行迁移</summary>
|
||||
public bool AutoMigrate { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// 是否在迁移前删除并重建当前连接指向的数据库。
|
||||
/// 仅用于切换数据库类型或本地开发重建库;生产环境默认必须保持 false。
|
||||
/// </summary>
|
||||
public bool RecreateDatabase { get; set; } = false;
|
||||
|
||||
/// <summary>是否启用详细日志(会打印 SQL 语句)</summary>
|
||||
public bool EnableDetailedLog { get; set; } = false;
|
||||
|
||||
/// <summary>连接超时(秒)</summary>
|
||||
public int Timeout { get; set; } = 30;
|
||||
|
||||
// ---- 快捷构建方法 ----
|
||||
|
||||
/// <summary>SQLite 本地数据库</summary>
|
||||
public static DatabaseConfiguration ForSQLite(string dataSource = "app.db")
|
||||
{
|
||||
return new DatabaseConfiguration
|
||||
{
|
||||
Provider = DatabaseProvider.SQLite,
|
||||
ConnectionString = $"Data Source={dataSource}",
|
||||
AutoMigrate = true,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>MySQL 数据库</summary>
|
||||
public static DatabaseConfiguration ForMySQL(string server, string database, string user, string password, uint port = 3306)
|
||||
{
|
||||
return new DatabaseConfiguration
|
||||
{
|
||||
Provider = DatabaseProvider.MySQL,
|
||||
ConnectionString = $"Server={server};Port={port};Database={database};User={user};Password={password};",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>PostgreSQL 数据库</summary>
|
||||
public static DatabaseConfiguration ForPostgreSQL(string host, string database, string username, string password, int port = 5432)
|
||||
{
|
||||
return new DatabaseConfiguration
|
||||
{
|
||||
Provider = DatabaseProvider.PostgreSQL,
|
||||
ConnectionString = $"Host={host};Port={port};Database={database};Username={username};Password={password};",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>SQL Server 数据库</summary>
|
||||
public static DatabaseConfiguration ForSqlServer(string server, string database, string? user = null, string? password = null)
|
||||
{
|
||||
var connStr = string.IsNullOrEmpty(user)
|
||||
? $"Server={server};Database={database};Trusted_Connection=True;TrustServerCertificate=True;"
|
||||
: $"Server={server};Database={database};User Id={user};Password={password};TrustServerCertificate=True;";
|
||||
return new DatabaseConfiguration
|
||||
{
|
||||
Provider = DatabaseProvider.SqlServer,
|
||||
ConnectionString = connStr,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace FileShare_EFCore.Database
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库服务注册扩展 —— 在 Program.cs 中一行配置数据库。
|
||||
/// </summary>
|
||||
public static class DatabaseExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 注册数据库上下文及相关服务。
|
||||
/// </summary>
|
||||
/// <typeparam name="TContext">继承自 AppDbContext 的业务 DbContext</typeparam>
|
||||
public static IServiceCollection AddAppDatabase<TContext>(
|
||||
this IServiceCollection services,
|
||||
DatabaseConfiguration config)
|
||||
where TContext : AppDbContext
|
||||
{
|
||||
// 注册配置
|
||||
services.AddSingleton(config);
|
||||
|
||||
if (typeof(TContext) == typeof(AppDataContext))
|
||||
{
|
||||
services.AddProviderAppDataContext(config);
|
||||
services.AddScoped<DatabaseManager<TContext>>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
// 注册 DbContext
|
||||
services.AddDbContext<TContext>(options =>
|
||||
{
|
||||
AppDbContext.ConfigureProvider(options, config);
|
||||
});
|
||||
|
||||
// 注册数据库管理器
|
||||
services.AddScoped<DatabaseManager<TContext>>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
private static void AddProviderAppDataContext(this IServiceCollection services, DatabaseConfiguration config)
|
||||
{
|
||||
switch (config.Provider)
|
||||
{
|
||||
case DatabaseProvider.SQLite:
|
||||
services.AddDbContext<AppDataContext, SqliteAppDataContext>(options =>
|
||||
AppDbContext.ConfigureProvider(options, config));
|
||||
break;
|
||||
case DatabaseProvider.SqlServer:
|
||||
services.AddDbContext<AppDataContext, SqlServerAppDataContext>(options =>
|
||||
AppDbContext.ConfigureProvider(options, config));
|
||||
break;
|
||||
case DatabaseProvider.PostgreSQL:
|
||||
services.AddDbContext<AppDataContext, PostgreSqlAppDataContext>(options =>
|
||||
AppDbContext.ConfigureProvider(options, config));
|
||||
break;
|
||||
case DatabaseProvider.MySQL:
|
||||
services.AddDbContext<AppDataContext, MySqlAppDataContext>(options =>
|
||||
AppDbContext.ConfigureProvider(options, config));
|
||||
break;
|
||||
default:
|
||||
throw new NotSupportedException($"数据库提供程序 {config.Provider} 未注册。");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初始化数据库(在应用启动时调用一次)。
|
||||
/// </summary>
|
||||
public static IServiceProvider InitializeDatabase<TContext>(
|
||||
this IServiceProvider serviceProvider,
|
||||
Action<TContext, IServiceProvider?>? seeder = null)
|
||||
where TContext : AppDbContext
|
||||
{
|
||||
using var scope = serviceProvider.CreateScope();
|
||||
var dbManager = scope.ServiceProvider.GetRequiredService<DatabaseManager<TContext>>();
|
||||
|
||||
// 同步等待初始化(启动时阻塞)
|
||||
dbManager.InitializeAsync(seeder).GetAwaiter().GetResult();
|
||||
|
||||
return serviceProvider;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
using FileShare_Common.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace FileShare_EFCore.Database
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库管理器 —— 负责连接测试、自动迁移、种子数据、版本检查。
|
||||
/// 在应用启动时调用,确保数据库结构与应用代码同步。
|
||||
/// </summary>
|
||||
public class DatabaseManager<TContext> where TContext : AppDbContext
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库上下文实例。
|
||||
/// </summary>
|
||||
private readonly TContext _context;
|
||||
/// <summary>
|
||||
/// 数据库配置。
|
||||
/// </summary>
|
||||
private readonly DatabaseConfiguration _config;
|
||||
/// <summary>
|
||||
/// DI 服务提供程序(可选,用于种子数据中解析服务)。
|
||||
/// </summary>
|
||||
private readonly IServiceProvider? _serviceProvider;
|
||||
|
||||
/// <summary>
|
||||
/// 初始化数据库管理器。
|
||||
/// </summary>
|
||||
/// <param name="context">数据库上下文。</param>
|
||||
/// <param name="config">数据库配置。</param>
|
||||
/// <param name="serviceProvider">可选的 DI 容器。</param>
|
||||
public DatabaseManager(TContext context, DatabaseConfiguration config, IServiceProvider? serviceProvider = null)
|
||||
{
|
||||
_context = context;
|
||||
_config = config;
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初始化数据库:测试连接 → 自动迁移 → 种子数据。
|
||||
/// </summary>
|
||||
public async Task InitializeAsync(Action<TContext, IServiceProvider?>? seeder = null)
|
||||
{
|
||||
AppLog.Information(
|
||||
"正在初始化数据库 Provider={Provider}, AppVersion={AppVersion}",
|
||||
_config.Provider,
|
||||
GetApplicationVersion());
|
||||
|
||||
// 1. 自动迁移(如果启用)。MigrateAsync 会按迁移历史顺序执行全部待处理迁移,
|
||||
// 支持用户从较旧软件版本直接升级到当前版本。
|
||||
if (_config.AutoMigrate)
|
||||
{
|
||||
if (_config.RecreateDatabase)
|
||||
{
|
||||
AppLog.Warning(
|
||||
"RecreateDatabase=true,将删除并重建当前连接指向的数据库。Provider={Provider}",
|
||||
_config.Provider);
|
||||
|
||||
await _context.Database.EnsureDeletedAsync();
|
||||
}
|
||||
|
||||
await MigrateAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
var canConnect = await CanConnectAsync();
|
||||
if (!canConnect)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"无法连接到数据库 [{_config.Provider}],请检查连接字符串和数据库服务状态。");
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 种子数据
|
||||
if (seeder != null)
|
||||
{
|
||||
seeder(_context, _serviceProvider);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 测试数据库连接是否正常。
|
||||
/// </summary>
|
||||
public async Task<bool> CanConnectAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _context.Database.CanConnectAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行待处理的迁移。
|
||||
/// 使用 EF Core 原生迁移机制,自动检测并应用 Schema 变更。
|
||||
/// </summary>
|
||||
public async Task MigrateAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var appliedMigrations = (await _context.Database.GetAppliedMigrationsAsync()).ToList();
|
||||
var pendingMigrations = await _context.Database.GetPendingMigrationsAsync();
|
||||
|
||||
if (pendingMigrations.Any())
|
||||
{
|
||||
if (appliedMigrations.Count == 0)
|
||||
{
|
||||
AppLog.Information(
|
||||
"未检测到已应用迁移,将按当前 Provider={Provider} 从 0 构建完整表结构",
|
||||
_config.Provider);
|
||||
}
|
||||
|
||||
AppLog.Information(
|
||||
"当前已应用 {AppliedCount} 个迁移,检测到 {PendingCount} 个待执行迁移: {Migrations}",
|
||||
appliedMigrations.Count,
|
||||
pendingMigrations.Count(),
|
||||
string.Join(", ", pendingMigrations));
|
||||
|
||||
await _context.Database.MigrateAsync();
|
||||
|
||||
AppLog.Information("数据库迁移完成({Count} 个迁移已应用)", pendingMigrations.Count());
|
||||
}
|
||||
else
|
||||
{
|
||||
AppLog.Information("数据库已是最新版本,无需迁移");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
AppLog.Error(ex, "数据库迁移失败");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前应用程序的版本号,优先读取 AssemblyInformationalVersion,回退到 AssemblyVersion。
|
||||
/// </summary>
|
||||
/// <returns>应用程序版本字符串。</returns>
|
||||
private static string GetApplicationVersion()
|
||||
{
|
||||
var assembly = Assembly.GetEntryAssembly() ?? typeof(TContext).Assembly;
|
||||
return assembly
|
||||
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
|
||||
?.InformationalVersion
|
||||
?? assembly.GetName().Version?.ToString()
|
||||
?? "unknown";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取数据库当前版本信息。
|
||||
/// </summary>
|
||||
public async Task<DatabaseVersionInfo> GetVersionInfoAsync()
|
||||
{
|
||||
var appliedMigrations = await _context.Database.GetAppliedMigrationsAsync();
|
||||
var pendingMigrations = await _context.Database.GetPendingMigrationsAsync();
|
||||
|
||||
return new DatabaseVersionInfo
|
||||
{
|
||||
Provider = _config.Provider.ToString(),
|
||||
AppliedMigrations = appliedMigrations.ToList(),
|
||||
PendingMigrations = pendingMigrations.ToList(),
|
||||
IsLatest = !pendingMigrations.Any(),
|
||||
CanConnect = await CanConnectAsync(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成从指定迁移到最新版本的 SQL 脚本(用于生产环境审计)。
|
||||
/// </summary>
|
||||
public string GenerateMigrationScript(string? fromMigration = null)
|
||||
{
|
||||
var migrator = _context.GetService<IMigrator>();
|
||||
return fromMigration is null
|
||||
? migrator.GenerateScript()
|
||||
: migrator.GenerateScript(fromMigration);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 确保数据库已创建(不执行迁移,适用于简单场景)。
|
||||
/// </summary>
|
||||
public bool EnsureCreated()
|
||||
{
|
||||
return _context.Database.EnsureCreated();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数据库版本信息 DTO。
|
||||
/// </summary>
|
||||
public class DatabaseVersionInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取或设置数据库提供程序名称。
|
||||
/// </summary>
|
||||
public string Provider { get; set; } = string.Empty;
|
||||
/// <summary>
|
||||
/// 获取或设置已应用的迁移列表。
|
||||
/// </summary>
|
||||
public List<string> AppliedMigrations { get; set; } = new();
|
||||
/// <summary>
|
||||
/// 获取或设置待应用的迁移列表。
|
||||
/// </summary>
|
||||
public List<string> PendingMigrations { get; set; } = new();
|
||||
/// <summary>
|
||||
/// 获取或设置是否为最新版本。
|
||||
/// </summary>
|
||||
public bool IsLatest { get; set; }
|
||||
/// <summary>
|
||||
/// 获取或设置数据库是否可连接。
|
||||
/// </summary>
|
||||
public bool CanConnect { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace FileShare_EFCore.Database
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库提供程序注册表 —— 统一注册所有支持的提供程序配置委托。
|
||||
/// 具体使用哪个提供程序由各宿主项目决定:
|
||||
/// FileShare-API:从 appsettings.json 的 DatabaseConfiguration 节读取;
|
||||
/// FileShare-PC :固定使用 SQLite。
|
||||
/// </summary>
|
||||
public static class DatabaseProviderRegistry
|
||||
{
|
||||
/// <summary>
|
||||
/// 提供程序配置委托:optionsBuilder, connectionString, timeout → void
|
||||
/// </summary>
|
||||
public delegate void ProviderConfigurator(DbContextOptionsBuilder optionsBuilder, string connectionString, int timeout);
|
||||
|
||||
/// <summary>
|
||||
/// 保存已注册的数据库提供程序及其配置委托。
|
||||
/// </summary>
|
||||
private static readonly Dictionary<DatabaseProvider, ProviderConfigurator> _providers = new();
|
||||
|
||||
/// <summary>
|
||||
/// 注册一个数据库提供程序。
|
||||
/// </summary>
|
||||
public static void Register(DatabaseProvider provider, ProviderConfigurator configurator)
|
||||
{
|
||||
_providers[provider] = configurator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 尝试获取注册的提供程序配置。
|
||||
/// </summary>
|
||||
public static bool TryGet(DatabaseProvider provider, out ProviderConfigurator configurator)
|
||||
{
|
||||
return _providers.TryGetValue(provider, out configurator!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 注册所有内置提供程序的默认配置(四个包均已内置在 FileShare-EFCore 中)。
|
||||
/// 注册完成后由调用方根据自身需求选择具体的 <see cref="DatabaseProvider"/>。
|
||||
/// </summary>
|
||||
public static void RegisterDefaults()
|
||||
{
|
||||
Register(DatabaseProvider.SQLite, (opts, cs, timeout) =>
|
||||
opts.UseSqlite(cs, o => o.CommandTimeout(timeout)));
|
||||
|
||||
Register(DatabaseProvider.SqlServer, (opts, cs, timeout) =>
|
||||
opts.UseSqlServer(cs, o => { o.CommandTimeout(timeout); o.EnableRetryOnFailure(3); }));
|
||||
|
||||
Register(DatabaseProvider.PostgreSQL, (opts, cs, timeout) =>
|
||||
opts.UseNpgsql(cs, o => { o.CommandTimeout(timeout); o.EnableRetryOnFailure(3); }));
|
||||
|
||||
Register(DatabaseProvider.MySQL, (opts, cs, timeout) =>
|
||||
opts.UseMySQL(cs, o => o.CommandTimeout(timeout)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace FileShare_EFCore.Database
|
||||
{
|
||||
/// <summary>
|
||||
/// SQLite 专用 DbContext,用于隔离 SQLite 迁移集。
|
||||
/// </summary>
|
||||
public sealed class SqliteAppDataContext(DatabaseConfiguration dbConfig) : AppDataContext(dbConfig)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SQL Server 专用 DbContext,用于隔离 SQL Server 迁移集。
|
||||
/// </summary>
|
||||
public sealed class SqlServerAppDataContext(DatabaseConfiguration dbConfig) : AppDataContext(dbConfig)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PostgreSQL 专用 DbContext,用于隔离 PostgreSQL 迁移集。
|
||||
/// </summary>
|
||||
public sealed class PostgreSqlAppDataContext(DatabaseConfiguration dbConfig) : AppDataContext(dbConfig)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// MySQL 专用 DbContext,用于隔离 MySQL 迁移集。
|
||||
/// </summary>
|
||||
public sealed class MySqlAppDataContext(DatabaseConfiguration dbConfig) : AppDataContext(dbConfig)
|
||||
{
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user