added database seed

master
Young 7 months ago
parent 95aba3d268
commit e3d3724ef6

@ -0,0 +1,23 @@
using SqlSugar;
namespace Infrastructure.Seed;
public class DatabaseContext
{
public DatabaseContext(ISqlSugarClient sqlSugarClient)
{
if (sqlSugarClient is SqlSugarScope scope)
{
Database = scope;
}
}
public SqlSugarScope Database { get; private set; }
public DbType DbType { get; set; }
public SimpleClient<T> GetEntityDatabase<T>() where T : class, new()
{
return new SimpleClient<T>(Database);
}
}

@ -0,0 +1,22 @@
namespace Infrastructure.Seed;
public static class DatabaseContextExtensions
{
public static IServiceCollection GenerateTablesByClass<T>(this IServiceCollection services,
DatabaseSeed databaseSeed
) where T : class, new()
{
ArgumentNullException.ThrowIfNull(services);
databaseSeed.GenerateTablesByClass<T>();
return services;
}
public static IServiceCollection GenerateSeedAsync<T>(this IServiceCollection services,
DatabaseSeed databaseSeed, string seedFile)
where T : class, new()
{
ArgumentNullException.ThrowIfNull(services);
databaseSeed.GenerateSeedAsync<T>(seedFile);
return services;
}
}

@ -0,0 +1,76 @@
using Infrastructure.Utils;
using SqlSugar;
namespace Infrastructure.Seed;
public class DatabaseSeed(DatabaseContext databaseContext, ILogger<DatabaseSeed> logger)
{
public void GenerateTablesByClass<T>() where T : class, new()
{
if (databaseContext.DbType == DbType.Oracle)
{
throw new InvalidOperationException("暂不支持Oracle数据库");
}
else
{
databaseContext.Database.DbMaintenance.CreateDatabase();
}
try
{
var modelType = typeof(T);
var types = modelType.Assembly.DefinedTypes.Where(ti =>
ti.Namespace == modelType.Namespace
& ti.IsClass
&& ti.GetCustomAttribute<SugarTable>() != null)
.Select(ti => ti.AsType());
foreach (var type in types)
{
var tableName = type.GetCustomAttribute<SugarTable>()?.TableName ?? type.Name;
Console.WriteLine($"table is initializing: {tableName}");
databaseContext.Database.CodeFirst.InitTables(type);
}
}
catch (Exception e)
{
logger.LogError(e.Message);
throw;
}
}
public async void GenerateSeedAsync<T>(string seedFile) where T : class, new()
{
if (string.IsNullOrEmpty(seedFile))
{
throw new ArgumentException("Value cannot be null or empty.", nameof(seedFile));
}
if (!File.Exists(seedFile))
{
throw new ArgumentException("seed file not exist", nameof(seedFile));
}
try
{
if (await databaseContext.Database.Queryable<T>().AnyAsync())
{
return;
}
var json = await File.ReadAllTextAsync(seedFile, Encoding.UTF8);
if (string.IsNullOrEmpty(json))
{
return;
}
var data = json.Deserialize<List<T>>();
await databaseContext.GetEntityDatabase<T>().InsertRangeAsync(data);
}
catch (Exception e)
{
logger.LogError(e.Message);
throw;
}
}
}
Loading…
Cancel
Save