diff --git a/Lib/Tiobon.Core.Base.dll b/Lib/Tiobon.Core.Base.dll index a7526e1d..1f3f9926 100644 Binary files a/Lib/Tiobon.Core.Base.dll and b/Lib/Tiobon.Core.Base.dll differ diff --git a/Lib/Tiobon.Core.dll b/Lib/Tiobon.Core.dll index 630019ab..5f6f8fd6 100644 Binary files a/Lib/Tiobon.Core.dll and b/Lib/Tiobon.Core.dll differ diff --git a/Lib/Tiobon.Core.xml b/Lib/Tiobon.Core.xml index 76878d99..cf71e7ce 100644 --- a/Lib/Tiobon.Core.xml +++ b/Lib/Tiobon.Core.xml @@ -3466,6 +3466,144 @@ 备注 + + + 用户信息表 + + + + + 登录账号 + + + + + 登录密码 + + + + + 真实姓名 + + + + + 状态 + + + + + 部门 + + + + + 备注 + + + + + 创建时间 + + + + + 更新时间 + + + + + 关键业务修改时间 + + + + + 最后异常时间 + + + + + 错误次数 + + + + + 登录账号 + + + + + 租户Id + + + + + 用户信息表 + + + + + Id + 泛型主键Tkey + + + + + 业务数据
+ 多租户 (Id 隔离) +
+
+ + + 无需手动赋值 + + + + + 名称 + + + + + 金额 + + + + + 多租户-多表方案 业务表 子表
+
+
+ + + 多租户-多表方案 业务表
+
+
+ + + 名称 + + + + + 金额 + + + + + 多租户-多库方案 业务表
+ 公共库无需标记[MultiTenant]特性 +
+
+ + + 名称 + + + + + 金额 + + 添加选项配置 选项类型 @@ -3514,6 +3652,317 @@ 地址 + + + 异步添加种子数据 + + + + + + + + 种子初始化数据 + + + + + + + 迁移日志数据库 + + + + + + 初始化 多租户 + + + + + + + 初始化多库 + + + + + + + + 生成Controller层 + + sqlsugar实例 + 数据库链接ID + 数据库表名数组,默认空,生成所有表 + + + + + + 生成Model层 + + sqlsugar实例 + 数据库链接ID + 数据库表名数组,默认空,生成所有表 + + + + + + 生成IRepository层 + + sqlsugar实例 + 数据库链接ID + + 数据库表名数组,默认空,生成所有表 + + + + + 生成 IService 层 + + sqlsugar实例 + 数据库链接ID + + 数据库表名数组,默认空,生成所有表 + + + + + 生成 Repository 层 + + sqlsugar实例 + 数据库链接ID + + 数据库表名数组,默认空,生成所有表 + + + + + 生成 Service 层 + + sqlsugar实例 + 数据库链接ID + + 数据库表名数组,默认空,生成所有表 + + + + + 根据数据库表生产Controller层 + + + 数据库链接ID + 实体类存放路径 + 命名空间 + 生产指定的表 + 实现接口 + + 是否序列化 + + + + 根据数据库表生产Model层 + + + 数据库链接ID + 实体类存放路径 + 命名空间 + 生产指定的表 + 实现接口 + + 是否序列化 + + + + 根据数据库表生产IRepository层 + + + 数据库链接ID + 实体类存放路径 + 命名空间 + 生产指定的表 + 实现接口 + + + + + 根据数据库表生产IServices层 + + + 数据库链接ID + 实体类存放路径 + 命名空间 + 生产指定的表 + 实现接口 + + + + + 根据数据库表生产 Repository 层 + + + 数据库链接ID + 实体类存放路径 + 命名空间 + 生产指定的表 + 实现接口 + + + + + 根据数据库表生产 Services 层 + + + 数据库链接ID + 实体类存放路径 + 命名空间 + 生产指定的表 + 实现接口 + + + + + 根据模板内容批量生成文件 + + 类文件字符串list + 生成路径 + 文件名格式模板 + + + + 种子数据 接口 + + + + + + 初始化种子数据
+ 只要表不存在数据,程序启动就会自动初始化 +
+ +
+ + + 种子数据
+ 存在不操作、不存在Insert
+ 适合系统内置数据,项目开发后续增加内置数据 +
+ +
+ + + 自定义操作
+ 以上满不足了,可以自己编写 +
+ + +
+ + + 连接字符串 + Tiobon.Core + + + + + 连接字符串 + Tiobon.Core + + + + + 数据库类型 + Tiobon.Core + + + + + 数据连接对象 + Tiobon.Core + + + + + 功能描述:构造函数 + 作  者:Tiobon.Core + + + + + 功能描述:获取数据库处理对象 + 作  者:Tiobon.Core + + 返回值 + + + + 功能描述:根据实体类生成数据库表 + 作  者:Tiobon.Core + + 是否备份表 + 指定的实体 + + + + 功能描述:根据实体类生成数据库表 + 作  者:Tiobon.Core + + 是否备份表 + 指定的实体 + + + + 功能描述:设置初始化参数 + 作  者:Tiobon.Core + + 连接字符串 + 数据库类型 + + + + 功能描述:创建一个链接配置 + 作  者:Tiobon.Core + + 是否自动关闭连接 + 是否夸类事务 + ConnectionConfig + + + + 功能描述:获取一个自定义的DB + 作  者:Tiobon.Core + + config + 返回值 + + + + 功能描述:获取一个自定义的数据库处理对象 + 作  者:Tiobon.Core + + sugarClient + 返回值 + + + + 功能描述:获取一个自定义的数据库处理对象 + 作  者:Tiobon.Core + + config + 返回值 + + + + 初始化 业务数据 + + + + + 租户 种子数据 + + diff --git a/Tiobon.CodeGenerator/Program.cs b/Tiobon.CodeGenerator/Program.cs index 14a3f666..686c95f8 100644 --- a/Tiobon.CodeGenerator/Program.cs +++ b/Tiobon.CodeGenerator/Program.cs @@ -1,7 +1,7 @@ using Microsoft.Extensions.DependencyInjection; using SqlSugar; using Tiobon.Core; -using Tiobon.Core.Common.Seed; +using Tiobon.Core.Seed; using Tiobon.Core.DB; using Tiobon.Core.DB.Dapper.Extensions; using Tiobon.Core.Extensions; diff --git a/Tiobon.Core.Api/Controllers/DbFirst/DbFirstController.cs b/Tiobon.Core.Api/Controllers/DbFirst/DbFirstController.cs index 70813862..f09c7506 100644 --- a/Tiobon.Core.Api/Controllers/DbFirst/DbFirstController.cs +++ b/Tiobon.Core.Api/Controllers/DbFirst/DbFirstController.cs @@ -1,7 +1,6 @@ -using Tiobon.Core.Common.DB; -using Tiobon.Core.Common.Seed; -using SqlSugar; +using SqlSugar; using Tiobon.Core.DB; +using Tiobon.Core.Seed; namespace Tiobon.Core.Controllers; diff --git a/Tiobon.Core.Common/Seed/DBSeed.cs b/Tiobon.Core.Common/Seed/DBSeed.cs deleted file mode 100644 index d201920a..00000000 --- a/Tiobon.Core.Common/Seed/DBSeed.cs +++ /dev/null @@ -1,643 +0,0 @@ -using Newtonsoft.Json; -using SqlSugar; -using System.Diagnostics; -using System.Reflection; -using System.Text; -using Tiobon.Core.Common.DB; -using Tiobon.Core.Extensions; -using Tiobon.Core.Const; -using Tiobon.Core.DB; -using Tiobon.Core.Helper; -using Tiobon.Core.Model.Models; -using Tiobon.Core.Model.Tenants; -using Tiobon.Core.Model; - -namespace Tiobon.Core.Common.Seed; - -public class DBSeed -{ - private static string SeedDataFolder = "TiobonCore.Data.json/{0}.tsv"; - - - /// - /// 异步添加种子数据 - /// - /// - /// - /// - public static async Task SeedAsync(MyContext myContext, string WebRootPath) - { - try - { - if (string.IsNullOrEmpty(WebRootPath)) - { - throw new Exception("获取wwwroot路径时,异常!"); - } - - SeedDataFolder = Path.Combine(WebRootPath, SeedDataFolder); - - Console.WriteLine("************ Tiobon.Core DataBase Set *****************"); - Console.WriteLine($"Master DB ConId: {myContext.Db.CurrentConnectionConfig.ConfigId}"); - Console.WriteLine($"Master DB Type: {myContext.Db.CurrentConnectionConfig.DbType}"); - Console.WriteLine($"Master DB ConnectString: {myContext.Db.CurrentConnectionConfig.ConnectionString}"); - Console.WriteLine(); - if (BaseDBConfig.MainConfig.SlaveConnectionConfigs.AnyNoException()) - { - var index = 0; - BaseDBConfig.MainConfig.SlaveConnectionConfigs.ForEach(m => - { - index++; - Console.WriteLine($"Slave{index} DB HitRate: {m.HitRate}"); - Console.WriteLine($"Slave{index} DB ConnectString: {m.ConnectionString}"); - Console.WriteLine($"--------------------------------------"); - }); - } - else if (BaseDBConfig.ReuseConfigs.AnyNoException()) - { - var index = 0; - BaseDBConfig.ReuseConfigs.ForEach(m => - { - index++; - Console.WriteLine($"Reuse{index} DB ID: {m.ConfigId}"); - Console.WriteLine($"Reuse{index} DB Type: {m.DbType}"); - Console.WriteLine($"Reuse{index} DB ConnectString: {m.ConnectionString}"); - Console.WriteLine($"--------------------------------------"); - }); - } - - Console.WriteLine(); - - // 创建数据库 - Console.WriteLine($"Create Database(The Db Id:{MyContext.ConnId})..."); - - if (MyContext.DbType != SqlSugar.DbType.Oracle && MyContext.DbType != SqlSugar.DbType.Dm) - { - myContext.Db.DbMaintenance.CreateDatabase(); - ConsoleHelper.WriteSuccessLine($"Database created successfully!"); - } - else - { - //Oracle 数据库不支持该操作 - ConsoleHelper.WriteSuccessLine($"Oracle 数据库不支持该操作,可手动创建Oracle/Dm数据库!"); - } - - // 创建数据库表,遍历指定命名空间下的class, - // 注意不要把其他命名空间下的也添加进来。 - Console.WriteLine("Create Tables..."); - - var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory; - var referencedAssemblies = System.IO.Directory.GetFiles(path, "Tiobon.Core.Model.dll") - .Select(Assembly.LoadFrom).ToArray(); - var modelTypes = referencedAssemblies - .SelectMany(a => a.DefinedTypes) - .Select(type => type.AsType()) - .Where(x => x.IsClass && x.Namespace is "Tiobon.Core.Model.Models") - .Where(s => !s.IsDefined(typeof(MultiTenantAttribute), false)) - .ToList(); - modelTypes.ForEach(t => - { - // 这里只支持添加表,不支持删除 - // 如果想要删除,数据库直接右键删除,或者联系SqlSugar作者; - if (!myContext.Db.DbMaintenance.IsAnyTable(t.Name)) - { - Console.WriteLine(t.Name); - myContext.Db.CodeFirst.SplitTables().InitTables(t); - } - }); - ConsoleHelper.WriteSuccessLine($"Tables created successfully!"); - Console.WriteLine(); - - if (AppSettings.app(new string[] { "AppSettings", "SeedDBDataEnabled" }).ObjToBool()) - { - JsonSerializerSettings setting = new JsonSerializerSettings(); - JsonConvert.DefaultSettings = new Func(() => - { - //日期类型默认格式化处理 - setting.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat; - setting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; - - //空值处理 - setting.NullValueHandling = NullValueHandling.Ignore; - - //高级用法九中的Bool类型转换 设置 - //setting.Converters.Add(new BoolConvert("是,否")); - - return setting; - }); - - Console.WriteLine($"Seeding database data (The Db Id:{MyContext.ConnId})..."); - - //var importer = new ExcelImporter(); - - #region TiobonArticle - - if (!await myContext.Db.Queryable().AnyAsync()) - { - myContext.GetEntityDB().InsertRange( - JsonHelper.ParseFormByJson>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "TiobonArticle"), Encoding.UTF8))); - Console.WriteLine("Table:TiobonArticle created success!"); - } - else - { - Console.WriteLine("Table:TiobonArticle already exists..."); - } - - #endregion - - - #region Modules - - if (!await myContext.Db.Queryable().AnyAsync()) - { - var data = JsonConvert.DeserializeObject>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "Modules"), Encoding.UTF8), setting); - - myContext.GetEntityDB().InsertRange(data); - Console.WriteLine("Table:Modules created success!"); - } - else - { - Console.WriteLine("Table:Modules already exists..."); - } - - #endregion - - - #region Permission - - if (!await myContext.Db.Queryable().AnyAsync()) - { - var data = JsonConvert.DeserializeObject>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "Permission"), Encoding.UTF8), setting); - - myContext.GetEntityDB().InsertRange(data); - Console.WriteLine("Table:Permission created success!"); - } - else - { - Console.WriteLine("Table:Permission already exists..."); - } - - #endregion - - - #region Role - - if (!await myContext.Db.Queryable().AnyAsync()) - { - var data = JsonConvert.DeserializeObject>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "Role"), Encoding.UTF8), setting); - //using var stream = new FileStream(Path.Combine(WebRootPath, "TiobonCore.Data.excel", "Role.xlsx"), FileMode.Open); - //var result = await importer.Import(stream); - //var data = result.Data.ToList(); - - myContext.GetEntityDB().InsertRange(data); - Console.WriteLine("Table:Role created success!"); - } - else - { - Console.WriteLine("Table:Role already exists..."); - } - - #endregion - - - #region RoleModulePermission - - if (!await myContext.Db.Queryable().AnyAsync()) - { - var data = JsonConvert.DeserializeObject>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "RoleModulePermission"), Encoding.UTF8), - setting); - - myContext.GetEntityDB().InsertRange(data); - Console.WriteLine("Table:RoleModulePermission created success!"); - } - else - { - Console.WriteLine("Table:RoleModulePermission already exists..."); - } - - #endregion - - - #region Topic - - //if (!await myContext.Db.Queryable().AnyAsync()) - //{ - // var data = JsonConvert.DeserializeObject>( - // FileHelper.ReadFile(string.Format(SeedDataFolder, "Topic"), Encoding.UTF8), setting); - - // myContext.GetEntityDB().InsertRange(data); - // Console.WriteLine("Table:Topic created success!"); - //} - //else - //{ - // Console.WriteLine("Table:Topic already exists..."); - //} - - #endregion - - - #region TopicDetail - - //if (!await myContext.Db.Queryable().AnyAsync()) - //{ - // var data = JsonConvert.DeserializeObject>( - // FileHelper.ReadFile(string.Format(SeedDataFolder, "TopicDetail"), Encoding.UTF8), setting); - - // myContext.GetEntityDB().InsertRange(data); - // Console.WriteLine("Table:TopicDetail created success!"); - //} - //else - //{ - // Console.WriteLine("Table:TopicDetail already exists..."); - //} - - #endregion - - - #region UserRole - - if (!await myContext.Db.Queryable().AnyAsync()) - { - var data = JsonConvert.DeserializeObject>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "UserRole"), Encoding.UTF8), setting); - - myContext.GetEntityDB().InsertRange(data); - Console.WriteLine("Table:UserRole created success!"); - } - else - { - Console.WriteLine("Table:UserRole already exists..."); - } - - #endregion - - - #region sysUserInfo - - if (!await myContext.Db.Queryable().AnyAsync()) - { - var data = JsonConvert.DeserializeObject>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "sysUserInfo"), Encoding.UTF8), setting); - - myContext.GetEntityDB().InsertRange(data); - Console.WriteLine("Table:sysUserInfo created success!"); - } - else - { - Console.WriteLine("Table:sysUserInfo already exists..."); - } - - #endregion - - - #region TasksQz - - if (!await myContext.Db.Queryable().AnyAsync()) - { - var data = JsonConvert.DeserializeObject>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "TasksQz"), Encoding.UTF8), setting); - - myContext.GetEntityDB().InsertRange(data); - Console.WriteLine("Table:TasksQz created success!"); - } - else - { - Console.WriteLine("Table:TasksQz already exists..."); - } - - #endregion - - #region TasksLog - - if (!await myContext.Db.Queryable().AnyAsync()) - { - Console.WriteLine("Table:TasksLog created success!"); - } - else - { - Console.WriteLine("Table:TasksLog already exists..."); - } - - #endregion - - #region Department - - if (!await myContext.Db.Queryable().AnyAsync()) - { - var data = JsonConvert.DeserializeObject>( - FileHelper.ReadFile(string.Format(SeedDataFolder, "Department"), Encoding.UTF8), setting); - - myContext.GetEntityDB().InsertRange(data); - Console.WriteLine("Table:Department created success!"); - } - else - { - Console.WriteLine("Table:Department already exists..."); - } - - #endregion - - //种子初始化 - await SeedDataAsync(myContext.Db); - - ConsoleHelper.WriteSuccessLine($"Done seeding database!"); - } - - Console.WriteLine(); - } - catch (Exception ex) - { - throw new Exception( - $"1、若是Mysql,查看常见问题:https://github.com/anjoy8/Tiobon.Core/issues/148#issue-776281770 \n" + - $"2、若是Oracle,查看常见问题:https://github.com/anjoy8/Tiobon.Core/issues/148#issuecomment-752340231 \n" + - "3、其他错误:" + ex.Message); - } - } - - /// - /// 种子初始化数据 - /// - /// - /// - private static async Task SeedDataAsync(ISqlSugarClient db) - { - // 获取所有种子配置-初始化数据 - var seedDataTypes = AssemblysExtensions.GetAllAssemblies().SelectMany(s => s.DefinedTypes) - .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass) - .Where(u => - { - var esd = u.GetInterfaces() - .FirstOrDefault(i => i.HasImplementedRawGeneric(typeof(IEntitySeedData<>))); - if (esd is null) - { - return false; - } - - var eType = esd.GenericTypeArguments[0]; - if (eType.GetCustomAttribute() is null) - { - return true; - } - - return false; - }); - - if (!seedDataTypes.Any()) return; - foreach (var seedType in seedDataTypes) - { - dynamic instance = Activator.CreateInstance(seedType); - //初始化数据 - { - var seedData = instance.InitSeedData(); - if (seedData != null && Enumerable.Any(seedData)) - { - var entityType = seedType.GetInterfaces().First().GetGenericArguments().First(); - var entity = db.EntityMaintenance.GetEntityInfo(entityType); - - if (!await db.Queryable(entity.DbTableName, "").AnyAsync()) - { - await db.Insertable(Enumerable.ToList(seedData)).ExecuteCommandAsync(); - Console.WriteLine($"Table:{entity.DbTableName} init success!"); - } - } - } - - //种子数据 - { - var seedData = instance.SeedData(); - if (seedData != null && Enumerable.Any(seedData)) - { - var entityType = seedType.GetInterfaces().First().GetGenericArguments().First(); - var entity = db.EntityMaintenance.GetEntityInfo(entityType); - - await db.Storageable(Enumerable.ToList(seedData)).ExecuteCommandAsync(); - Console.WriteLine($"Table:{entity.DbTableName} seedData success!"); - } - } - - //自定义处理 - { - await instance.CustomizeSeedData(db); - } - } - } - - /// - /// 迁移日志数据库 - /// - /// - public static void MigrationLogs(MyContext myContext) - { - // 创建数据库表,遍历指定命名空间下的class, - // 注意不要把其他命名空间下的也添加进来。 - Console.WriteLine("Create Log Tables..."); - if (!myContext.Db.IsAnyConnection(SqlSugarConst.LogConfigId.ToLower())) - { - throw new ApplicationException("未配置日志数据库,请在appsettings.json中DBS节点中配置"); - } - - var logDb = myContext.Db.GetConnection(SqlSugarConst.LogConfigId.ToLower()); - Console.WriteLine($"Create log Database(The Db Id:{SqlSugarConst.LogConfigId.ToLower()})..."); - logDb.DbMaintenance.CreateDatabase(); - ConsoleHelper.WriteSuccessLine($"Log Database created successfully!"); - var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory; - var referencedAssemblies = System.IO.Directory.GetFiles(path, "Tiobon.Core.Model.dll") - .Select(Assembly.LoadFrom).ToArray(); - var modelTypes = referencedAssemblies - .SelectMany(a => a.DefinedTypes) - .Select(type => type.AsType()) - .Where(x => x.IsClass && x.Namespace != null && x.Namespace.StartsWith("Tiobon.Core.Model.Logs")) - .ToList(); - Stopwatch sw = Stopwatch.StartNew(); - - var tables = logDb.DbMaintenance.GetTableInfoList(); - - modelTypes.ForEach(t => - { - // 这里只支持添加修改表,不支持删除 - // 如果想要删除,数据库直接右键删除,或者联系SqlSugar作者; - if (!tables.Any(s => s.Name.Contains(t.Name))) - { - Console.WriteLine(t.Name); - if (t.GetCustomAttribute() != null) - { - logDb.CodeFirst.SplitTables().InitTables(t); - } - else - { - logDb.CodeFirst.InitTables(t); - } - } - }); - - sw.Stop(); - - $"Log Tables created successfully! {sw.ElapsedMilliseconds}ms".WriteSuccessLine(); - Console.WriteLine(); - } - - - /// - /// 初始化 多租户 - /// - /// - /// - public static async Task TenantSeedAsync(MyContext myContext) - { - var tenants = await myContext.Db.Queryable().Where(s => s.TenantType == TenantTypeEnum.Db) - .ToListAsync(); - if (tenants.Any()) - { - Console.WriteLine($@"Init Multi Tenant Db"); - foreach (var tenant in tenants) - { - Console.WriteLine($@"Init Multi Tenant Db : {tenant.ConfigId}/{tenant.Name}"); - await InitTenantSeedAsync(myContext.Db.AsTenant(), tenant.GetConnectionConfig()); - } - } - - tenants = await myContext.Db.Queryable().Where(s => s.TenantType == TenantTypeEnum.Tables) - .ToListAsync(); - if (tenants.Any()) - { - await InitTenantSeedAsync(myContext, tenants); - } - } - - #region 多租户 多表 初始化 - - private static async Task InitTenantSeedAsync(MyContext myContext, List tenants) - { - ConsoleHelper.WriteInfoLine($"Init Multi Tenant Tables : {myContext.Db.CurrentConnectionConfig.ConfigId}"); - - // 获取所有实体表-初始化租户业务表 - var entityTypes = TenantUtil.GetTenantEntityTypes(TenantTypeEnum.Tables); - if (!entityTypes.Any()) return; - - foreach (var sysTenant in tenants) - { - foreach (var entityType in entityTypes) - { - myContext.Db.CodeFirst - .As(entityType, entityType.GetTenantTableName(myContext.Db, sysTenant)) - .InitTables(entityType); - - Console.WriteLine($@"Init Tables:{entityType.GetTenantTableName(myContext.Db, sysTenant)}"); - } - - myContext.Db.SetTenantTable(sysTenant.Id.ToString()); - //多租户初始化种子数据 - await TenantSeedDataAsync(myContext.Db, TenantTypeEnum.Tables); - } - - ConsoleHelper.WriteSuccessLine( - $"Init Multi Tenant Tables : {myContext.Db.CurrentConnectionConfig.ConfigId} created successfully!"); - } - - #endregion - - #region 多租户 多库 初始化 - - /// - /// 初始化多库 - /// - /// - /// - /// - public static async Task InitTenantSeedAsync(ITenant itenant, ConnectionConfig config) - { - itenant.RemoveConnection(config.ConfigId); - itenant.AddConnection(config); - - var db = itenant.GetConnectionScope(config.ConfigId); - - db.DbMaintenance.CreateDatabase(); - ConsoleHelper.WriteSuccessLine($"Init Multi Tenant Db : {config.ConfigId} Database created successfully!"); - - Console.WriteLine($@"Init Multi Tenant Db : {config.ConfigId} Create Tables"); - - // 获取所有实体表-初始化租户业务表 - var entityTypes = TenantUtil.GetTenantEntityTypes(TenantTypeEnum.Db); - if (!entityTypes.Any()) return; - foreach (var entityType in entityTypes) - { - var splitTable = entityType.GetCustomAttribute(); - if (splitTable == null) - db.CodeFirst.InitTables(entityType); - else - db.CodeFirst.SplitTables().InitTables(entityType); - - Console.WriteLine(entityType.Name); - } - - //多租户初始化种子数据 - await TenantSeedDataAsync(db, TenantTypeEnum.Db); - } - - #endregion - - #region 多租户 种子数据 初始化 - - private static async Task TenantSeedDataAsync(ISqlSugarClient db, TenantTypeEnum tenantType) - { - // 获取所有种子配置-初始化数据 - var seedDataTypes = AssemblysExtensions.GetAllAssemblies().SelectMany(s => s.DefinedTypes) - .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass) - .Where(u => - { - var esd = u.GetInterfaces() - .FirstOrDefault(i => i.HasImplementedRawGeneric(typeof(IEntitySeedData<>))); - if (esd is null) - { - return false; - } - - var eType = esd.GenericTypeArguments[0]; - return eType.IsTenantEntity(tenantType); - }); - if (!seedDataTypes.Any()) return; - foreach (var seedType in seedDataTypes) - { - dynamic instance = Activator.CreateInstance(seedType); - //初始化数据 - { - var seedData = instance.InitSeedData(); - if (seedData != null && Enumerable.Any(seedData)) - { - var entityType = seedType.GetInterfaces().First().GetGenericArguments().First(); - var entity = db.EntityMaintenance.GetEntityInfo(entityType); - - if (!await db.Queryable(entity.DbTableName, "").AnyAsync()) - { - await db.Insertable(Enumerable.ToList(seedData)).ExecuteCommandAsync(); - Console.WriteLine($"Table:{entity.DbTableName} init success!"); - } - } - } - - //种子数据 - { - var seedData = instance.SeedData(); - if (seedData != null && Enumerable.Any(seedData)) - { - var entityType = seedType.GetInterfaces().First().GetGenericArguments().First(); - var entity = db.EntityMaintenance.GetEntityInfo(entityType); - - await db.Storageable(Enumerable.ToList(seedData)).ExecuteCommandAsync(); - Console.WriteLine($"Table:{entity.DbTableName} seedData success!"); - } - } - - //自定义处理 - { - await instance.CustomizeSeedData(db); - } - } - } - - #endregion -} \ No newline at end of file diff --git a/Tiobon.Core.Common/Seed/FrameSeed.cs b/Tiobon.Core.Common/Seed/FrameSeed.cs deleted file mode 100644 index c2c5fefa..00000000 --- a/Tiobon.Core.Common/Seed/FrameSeed.cs +++ /dev/null @@ -1,1091 +0,0 @@ -using Tiobon.Core.DB.Dapper; -using SqlSugar; -using System.Text; - -namespace Tiobon.Core.Common.Seed; - -public class FrameSeed -{ - - public static string path = AppDomain.CurrentDomain.BaseDirectory - .Replace("Tiobon.Core.Api\\bin\\Debug\\net8.0\\", null) - .Replace("Tiobon.CodeGenerator\\bin\\Debug\\net8.0\\", null) - .Replace("Tiobon.CodeGenerator\\bin\\Release\\net8.0\\", null); - /// - /// 生成Controller层 - /// - /// sqlsugar实例 - /// 数据库链接ID - /// 数据库表名数组,默认空,生成所有表 - /// - /// - public static bool CreateControllers(SqlSugarScope sqlSugarClient, string ConnId = null, bool isMuti = false, string[] tableNames = null) - { - Create_Controller_ClassFileByDBTalbe(sqlSugarClient, ConnId, path + $@"Tiobon.Core.Api\Controllers", "Tiobon.Core.Api.Controllers", tableNames, "", isMuti); - return true; - } - - /// - /// 生成Model层 - /// - /// sqlsugar实例 - /// 数据库链接ID - /// 数据库表名数组,默认空,生成所有表 - /// - /// - public static bool CreateModels(SqlSugarScope sqlSugarClient, string ConnId, bool isMuti = false, string[] tableNames = null) - { - Create_Model_ClassFileByDBTalbe(sqlSugarClient, ConnId, path + $@"Tiobon.Core.Model", "Tiobon.Core.Model.Models", tableNames, "", isMuti); - return true; - } - - /// - /// 生成IRepository层 - /// - /// sqlsugar实例 - /// 数据库链接ID - /// - /// 数据库表名数组,默认空,生成所有表 - /// - public static bool CreateIRepositorys(SqlSugarScope sqlSugarClient, string ConnId, bool isMuti = false, string[] tableNames = null) - { - Create_IRepository_ClassFileByDBTalbe(sqlSugarClient, ConnId, path + $@"Tiobon.Core.IRepository", "Tiobon.Core.IRepository", tableNames, "", isMuti); - return true; - } - - - - /// - /// 生成 IService 层 - /// - /// sqlsugar实例 - /// 数据库链接ID - /// - /// 数据库表名数组,默认空,生成所有表 - /// - public static bool CreateIServices(SqlSugarScope sqlSugarClient, string ConnId, bool isMuti = false, string[] tableNames = null) - { - Create_IServices_ClassFileByDBTalbe(sqlSugarClient, ConnId, path + $@"Tiobon.Core.IServices", "Tiobon.Core.IServices", tableNames, "", isMuti); - return true; - } - - - - /// - /// 生成 Repository 层 - /// - /// sqlsugar实例 - /// 数据库链接ID - /// - /// 数据库表名数组,默认空,生成所有表 - /// - public static bool CreateRepository(SqlSugarScope sqlSugarClient, string ConnId, bool isMuti = false, string[] tableNames = null) - { - Create_Repository_ClassFileByDBTalbe(sqlSugarClient, ConnId, path + $@"Tiobon.Core.Repository", "Tiobon.Core.Repository", tableNames, "", isMuti); - return true; - } - - - - /// - /// 生成 Service 层 - /// - /// sqlsugar实例 - /// 数据库链接ID - /// - /// 数据库表名数组,默认空,生成所有表 - /// - public static bool CreateServices(SqlSugarScope sqlSugarClient, string ConnId, bool isMuti = false, string[] tableNames = null) - { - Create_Services_ClassFileByDBTalbe(sqlSugarClient, ConnId, path + $@"Tiobon.Core.Services", "Tiobon.Core.Services", tableNames, "", isMuti); - return true; - } - - - #region 根据数据库表生产Controller层 - - /// - /// 根据数据库表生产Controller层 - /// - /// - /// 数据库链接ID - /// 实体类存放路径 - /// 命名空间 - /// 生产指定的表 - /// 实现接口 - /// - /// 是否序列化 - private static void Create_Controller_ClassFileByDBTalbe( - SqlSugarScope sqlSugarClient, - string ConnId, - string strPath, - string strNameSpace, - string[] lstTableNames, - string strInterface, - bool isMuti = false, - bool blnSerializable = false) - { - var IDbFirst = sqlSugarClient.DbFirst; - if (lstTableNames != null && lstTableNames.Length > 0) - { - IDbFirst = IDbFirst.Where(lstTableNames); - } - - var tableName = lstTableNames[0]; - var groupName = tableName.Split('_')[0]; - // var ls = IDbFirst.IsCreateDefaultValue().IsCreateAttribute() - - // .SettingClassTemplate(p => p = - //@"namespace " + strNameSpace + @" - //{ - // /// - // /// {ClassName} - // /// - // [Route(""api/[controller]"")] - // [ApiController, GlobalActionFilter] - // [Authorize(Permissions.Name), ApiExplorerSettings(GroupName = Grouping.GroupName_" + groupName + @")] - // public class {ClassName}Controller : ControllerBase - // { - // #region 初始化 - // /// - // /// 服务器接口,因为是模板生成,所以首字母是大写的,自己可以重构下 - // /// - // private readonly I{ClassName}Services _{ClassName}Services; - - // public {ClassName}Controller(I{ClassName}Services {ClassName}Services) - // { - // _{ClassName}Services = {ClassName}Services; - // } - // #endregion - - // #region 基础接口 - - // #region 查询 - // /// - // /// {ClassName} -- 根据条件查询数据 - // /// - // /// 条件 - // /// - // [HttpGet] - // public async Task>> Get([FromFilter] QueryFilter filter) - // { - // var response = await _{ClassName}Services.QueryFilterPage(filter); - // return new ServiceResult>() { msg = ""获取成功"", success = true, response = response }; - // } - - // /// - // /// {ClassName} -- 根据Id查询数据 - // /// - // /// 主键ID - // /// - // [HttpGet(""{Id}"")] - // public async Task> Get(string Id) - // { - // var entity = await _{ClassName}Services.QueryById(Id); - // if (entity == null) - // return ServiceResult<{ClassName}Dto>.Fail(""获取失败""); - // else - // return new ServiceResult<{ClassName}Dto>() { msg = ""获取成功"", success = true, response = entity }; - // } - // #endregion - - // #region 新增 - // /// - // /// {ClassName} -- 新增数据 - // /// - // /// - // /// - // [HttpPost] - // public async Task> Post([FromBody] Insert{ClassName}Input insertModel) - // { - // var data = ServiceResult.Success(""获取成功"", null); - - // var id = await _{ClassName}Services.Add(insertModel); - // data.success = id > 0; - // if (data.success) - // data.response = id.ObjToString(); - - // return data; - // } - // #endregion - - // #region 更新 - // /// - // /// {ClassName} -- 更新数据 - // /// - // /// - // /// - // /// - // [HttpPut(""{Id}"")] - // public async Task Put(long Id, [FromBody] Edit{ClassName}Input editModel) - // { - // var data = MessageModel.Success(""更新成功""); - // data.success = await _{ClassName}Services.Update(Id, editModel); - // if (!data.success) - // data.msg = ""更新失败""; - - // return data; - // } - // #endregion - - // #region 删除 - // /// - // /// {ClassName} -- 删除数据 - // /// - // /// - // /// - // [HttpDelete(""{Id}"")] - // public async Task Delete(long Id) - // { - // var data = MessageModel.Success(""删除成功""); - // var entity = await _{ClassName}Services.QueryById(Id); - // if (entity == null) - // return MessageModel.Fail(""删除失败""); - - // entity.IsEnable = 0; - // data.success = await _{ClassName}Services.Update(entity); - // if (!data.success) - // data.msg = ""删除失败""; - // return data; - // } - // #endregion - - // #endregion - // } - //}") - - // .ToClassStringList(strNameSpace); - - #region 获取表中文名 - string sql = @"SELECT f.value TableName - FROM sysobjects d - LEFT JOIN sys.extended_properties f - ON d.id = f.major_id AND f.minor_id = 0 - WHERE d.name = '{0}'"; - sql = string.Format(sql, tableName); - string TableCnName = Convert.ToString(DbAccess.ExecuteScalar(sql, null)); - if (string.IsNullOrWhiteSpace(TableCnName)) TableCnName = tableName; - #endregion - - var ls = IDbFirst.IsCreateDefaultValue().IsCreateAttribute() - - .SettingClassTemplate(p => p = - @"namespace " + strNameSpace + @"; - -/// -/// " + TableCnName + @"(Controller) -/// -[Route(""api/[controller]"")] -[ApiController, GlobalActionFilter] -[Authorize(Permissions.Name), ApiExplorerSettings(GroupName = Grouping.GroupName_" + groupName + @")] -public class {ClassName}Controller : BaseController -{ - public {ClassName}Controller(I{ClassName}Services service) : base(service) - { - } -}") - - .ToClassStringList(strNameSpace); - - Dictionary newdic = new Dictionary(); - //循环处理 首字母小写 并插入新的 Dictionary - foreach (KeyValuePair item in ls) - { - string newkey = "_" + item.Key.First().ToString().ToLower() + item.Key.Substring(1); - string newvalue = item.Value.Replace("_" + item.Key, newkey); - newdic.Add(item.Key, newvalue); - } - CreateFilesByClassStringList(newdic, strPath + "/" + groupName, "{0}Controller"); - } - #endregion - - - #region 根据数据库表生产Model层 - - /// - /// 根据数据库表生产Model层 - /// - /// - /// 数据库链接ID - /// 实体类存放路径 - /// 命名空间 - /// 生产指定的表 - /// 实现接口 - /// - /// 是否序列化 - private static void Create_Model_ClassFileByDBTalbe( - SqlSugarScope sqlSugarClient, - string ConnId, - string strPath, - string strNameSpace, - string[] lstTableNames, - string strInterface, - bool isMuti = false, - bool blnSerializable = false) - { - //多库文件分离 - if (isMuti) - { - strPath = strPath + @"\Models\" + ConnId; - strNameSpace = strNameSpace + "." + ConnId; - } - - var IDbFirst = sqlSugarClient.DbFirst; - if (lstTableNames != null && lstTableNames.Length > 0) - { - IDbFirst = IDbFirst.Where(lstTableNames); - } - var ls = IDbFirst.IsCreateDefaultValue().IsCreateAttribute() - - .SettingClassTemplate(p => p = -@"{using} - -namespace " + strNameSpace + @" -{ -{ClassDescription} - [SugarTable( ""{ClassName}"", """ + ConnId + @"""), Entity(TableCnName = ""{ClassName}"", TableName = ""{ClassName}"")]" + (blnSerializable ? "\n [Serializable]" : "") + @" - public class {ClassName}" + (string.IsNullOrEmpty(strInterface) ? "" : (" : " + strInterface)) + @" - { - public {ClassName}() - { - } -{PropertyName} - } -}") - //.SettingPropertyDescriptionTemplate(p => p = string.Empty) - .SettingPropertyTemplate(p => p = -@"{SugarColumn} - public {PropertyType} {PropertyName} { get; set; }") - - //.SettingConstructorTemplate(p => p = " this._{PropertyName} ={DefaultValue};") - - .ToClassStringList(strNameSpace); - - StringBuilder build = new StringBuilder(); - var tableName = lstTableNames[0]; - var groupName = tableName.Split('_')[0]; - string sql = @"SELECT A.name AS table_name, - B.name AS column_name, - D.data_type, - C.value AS column_description, - D.NUMERIC_PRECISION, D.NUMERIC_SCALE,D.CHARACTER_MAXIMUM_LENGTH - FROM sys.tables A - INNER JOIN sys.columns B ON B.object_id = A.object_id - LEFT JOIN sys.extended_properties C - ON C.major_id = B.object_id AND C.minor_id = B.column_id - LEFT JOIN information_schema.columns D - ON D.column_name = B.name AND D.TABLE_NAME = '{0}' - WHERE A.name = '{0}' ORDER BY B.column_id ASC"; - sql = string.Format(sql, tableName); - var dtColumn = sqlSugarClient.Ado.GetDataTable(sql); - - #region 获取表中文名 - sql = @"SELECT f.value TableName - FROM sysobjects d - LEFT JOIN sys.extended_properties f - ON d.id = f.major_id AND f.minor_id = 0 - WHERE d.name = '{0}'"; - sql = string.Format(sql, tableName); - string TableCnName = Convert.ToString(DbAccess.ExecuteScalar(sql, null)); - if (string.IsNullOrWhiteSpace(TableCnName)) TableCnName = tableName; - #endregion - - build.Append("/* 代码由框架生成,任何更改都可能导致被代码生成器覆盖,可自行修改。\r\n"); - build.Append("* " + tableName + ".cs\r\n"); - build.Append("*\r\n"); - build.Append("*功 能: N / A\r\n"); - build.Append("* 类 名: " + tableName + "\r\n"); - build.Append("*\r\n"); - build.Append("* Ver 变更日期 负责人 变更内容\r\n"); - build.Append("* ───────────────────────────────────\r\n"); - build.Append("*V0.01 " + DateTime.Now.ToString() + " SimonHsiao 初版\r\n"); - build.Append("*\r\n"); - build.Append("* Copyright(c) " + DateTime.Now.Year + " Tiobon Corporation. All Rights Reserved.\r\n"); - build.Append("*┌──────────────────────────────────┐\r\n"); - build.Append("*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │\r\n"); - build.Append("*│ 作者:SimonHsiao │\r\n"); - build.Append("*└──────────────────────────────────┘\r\n"); - build.Append("*/ \r\n"); - build.Append("using System.ComponentModel;\r\n"); - build.Append("using System.ComponentModel.DataAnnotations;\r\n"); - build.Append("using SqlSugar;\r\n"); - build.Append("\r\n"); - build.Append("namespace Tiobon.Core.Model.Models\r\n"); - build.Append("{\r\n"); - build.Append("\r\n"); - build.Append(" /// \r\n"); - build.Append(" /// " + TableCnName + " (Model)\r\n"); - build.Append(" /// \r\n"); - build.Append(@" [SugarTable(" + "\"" + tableName + "\"" + ", " + "\"" + tableName + "\"" + "), Entity(TableCnName = \"" + TableCnName + "\", TableName = \"" + tableName + "\")]\r\n"); - build.Append(" public class " + tableName + " : BasePoco\r\n"); - build.Append(" {\r\n"); - - #region 属性 - //build.Append("\r\n"); - - #region 处理表字段 - string columnCode = string.Empty; - string dataType = string.Empty; - string column_description = string.Empty; - string NUMERIC_PRECISION = string.Empty; - string NUMERIC_SCALE = string.Empty; - string CHARACTER_MAXIMUM_LENGTH = string.Empty; - - string[] a = { - "Id", "IsEnable", "OperateLogID", "CreateBy", "CreateTime", - "CreateProg", "CreateIP", "UpdateBy", "UpdateTime", "UpdateProg","UpdateIP" - - }; - - for (int i = 0; i < dtColumn.Rows.Count; i++) - { - columnCode = dtColumn.Rows[i]["column_name"].ToString(); - dataType = dtColumn.Rows[i]["data_type"].ToString(); - column_description = dtColumn.Rows[i]["column_description"].ToString(); - NUMERIC_PRECISION = dtColumn.Rows[i]["NUMERIC_PRECISION"].ToString(); - NUMERIC_SCALE = dtColumn.Rows[i]["NUMERIC_SCALE"].ToString(); - CHARACTER_MAXIMUM_LENGTH = dtColumn.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString(); - - if (string.IsNullOrWhiteSpace(column_description)) - column_description = columnCode; - - if (a.Contains(columnCode)) - continue; - - build.Append("\r\n"); - build.Append(" /// \r\n"); - build.Append(" /// " + column_description + "\r\n"); - build.Append(" /// \r\n"); - if (dataType == "decimal") - build.Append($" [Display(Name = \"" + columnCode + "\"), Description(\"" + column_description + "\"), Column(TypeName = \"decimal(" + NUMERIC_PRECISION + "," + NUMERIC_SCALE + ")\")]\r\n"); - else if (dataType == "varchar" || dataType == "nvarchar" || dataType == "char" || dataType == "text") - build.Append(" [Display(Name = \"" + columnCode + "\"), Description(\"" + column_description + "\"), MaxLength(" + CHARACTER_MAXIMUM_LENGTH + ", ErrorMessage = \"" + column_description + " 不能超过 " + CHARACTER_MAXIMUM_LENGTH + " 个字符\")]\r\n"); - else if (dataType == "decimal") - build.Append(" [Display(Name = \"" + columnCode + "\"), Description(\"" + column_description + "\")]\r\n"); - - switch (dataType) - { - #region 字符串 - case "varchar": - case "nvarchar": - case "char": - case "text": - { - build.Append(" public string " + columnCode + " { get; set; }\r\n"); - break; - } - #endregion - - #region 日期 - case "datetime": - case "date": - { - build.Append(" public DateTime? " + columnCode + " { get; set; }\r\n"); - break; - } - #endregion - - #region 数字 - case "decimal": - { - - build.Append(" public decimal? " + columnCode + " { get; set; }\r\n"); - } - break; - case "int": - { - - build.Append(" public int? " + columnCode + " { get; set; }\r\n"); - - break; - } - case "uniqueidentifier": - { - - build.Append(" public Guid? " + columnCode + " { get; set; }\r\n"); - - break; - } - case "bit": - { - - build.Append(" public bool? " + columnCode + " { get; set; }\r\n"); - - break; - } - case "bigint": - { - - build.Append(" public long? " + columnCode + " { get; set; }\r\n"); - - break; - } - #endregion - } - } - #endregion - #endregion - - - build.Append(" }\r\n"); - build.Append("}\r\n"); - - ls[tableName] = build.ToString(); - CreateFilesByClassStringList(ls, strPath + @"\Models\" + groupName, "{0}"); - - #region Base - build = new StringBuilder(); - ls = new Dictionary(); - build.Append("/* 代码由框架生成,任何更改都可能导致被代码生成器覆盖,可自行修改。\r\n"); - build.Append("* " + tableName + ".cs\r\n"); - build.Append("*\r\n"); - build.Append("*功 能: N / A\r\n"); - build.Append("* 类 名: " + tableName + "\r\n"); - build.Append("*\r\n"); - build.Append("* Ver 变更日期 负责人 变更内容\r\n"); - build.Append("* ───────────────────────────────────\r\n"); - build.Append("*V0.01 " + DateTime.Now.ToString() + " SimonHsiao 初版\r\n"); - build.Append("*\r\n"); - build.Append("* Copyright(c) " + DateTime.Now.Year + " Tiobon Corporation. All Rights Reserved.\r\n"); - build.Append("*┌──────────────────────────────────┐\r\n"); - build.Append("*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │\r\n"); - build.Append("*│ 作者:SimonHsiao │\r\n"); - build.Append("*└──────────────────────────────────┘\r\n"); - build.Append("*/ \r\n"); - build.Append("using System.ComponentModel;\r\n"); - build.Append("using System.ComponentModel.DataAnnotations;\r\n"); - build.Append("\r\n"); - build.Append("namespace Tiobon.Core.Model.Models\r\n"); - build.Append("{\r\n"); - build.Append("\r\n"); - build.Append(" /// \r\n"); - build.Append(" /// " + TableCnName + " (Dto.Base)\r\n"); - build.Append(" /// \r\n"); - build.Append(" public class " + tableName + "Base\r\n"); - build.Append(" {\r\n"); - - #region 属性 - //build.Append("\r\n"); - - #region 处理表字段 - - for (int i = 0; i < dtColumn.Rows.Count; i++) - { - columnCode = dtColumn.Rows[i]["column_name"].ToString(); - dataType = dtColumn.Rows[i]["data_type"].ToString(); - column_description = dtColumn.Rows[i]["column_description"].ToString(); - NUMERIC_PRECISION = dtColumn.Rows[i]["NUMERIC_PRECISION"].ToString(); - NUMERIC_SCALE = dtColumn.Rows[i]["NUMERIC_SCALE"].ToString(); - CHARACTER_MAXIMUM_LENGTH = dtColumn.Rows[i]["CHARACTER_MAXIMUM_LENGTH"].ToString(); - - if (string.IsNullOrWhiteSpace(column_description)) - column_description = columnCode; - - if (a.Contains(columnCode)) - continue; - - build.Append("\r\n"); - build.Append(" /// \r\n"); - build.Append(" /// " + column_description + "\r\n"); - build.Append(" /// \r\n"); - if (dataType == "decimal") - build.Append($" [Display(Name = \"" + columnCode + "\"), Description(\"" + column_description + "\"), Column(TypeName = \"decimal(" + NUMERIC_PRECISION + "," + NUMERIC_SCALE + ")\")]\r\n"); - else if (dataType == "varchar" || dataType == "nvarchar" || dataType == "char" || dataType == "text") - build.Append(" [Display(Name = \"" + columnCode + "\"), Description(\"" + column_description + "\"), MaxLength(" + CHARACTER_MAXIMUM_LENGTH + ", ErrorMessage = \"" + column_description + " 不能超过 " + CHARACTER_MAXIMUM_LENGTH + " 个字符\")]\r\n"); - else if (dataType == "decimal") - build.Append(" [Display(Name = \"" + columnCode + "\"), Description(\"" + column_description + "\")]\r\n"); - - switch (dataType) - { - #region 字符串 - case "varchar": - case "nvarchar": - case "char": - case "text": - { - build.Append(" public string " + columnCode + " { get; set; }\r\n"); - break; - } - #endregion - - #region 日期 - case "datetime": - case "date": - { - build.Append(" public DateTime? " + columnCode + " { get; set; }\r\n"); - break; - } - #endregion - - #region 数字 - case "decimal": - { - - build.Append(" public decimal? " + columnCode + " { get; set; }\r\n"); - } - break; - case "int": - { - - build.Append(" public int? " + columnCode + " { get; set; }\r\n"); - - break; - } - case "uniqueidentifier": - { - - build.Append(" public Guid? " + columnCode + " { get; set; }\r\n"); - - break; - } - case "bit": - { - - build.Append(" public bool? " + columnCode + " { get; set; }\r\n"); - - break; - } - case "bigint": - { - - build.Append(" public long? " + columnCode + " { get; set; }\r\n"); - - break; - } - #endregion - } - } - #endregion - #endregion - - - build.Append(" }\r\n"); - build.Append("}\r\n"); - - ls.Add(tableName + ".Dto.Base", build.ToString()); - CreateFilesByClassStringList(ls, strPath + @"\Base\" + groupName, "{0}"); - #endregion - - #region Insert - build = new StringBuilder(); - ls = new Dictionary(); - - build.Append("/* 代码由框架生成,任何更改都可能导致被代码生成器覆盖,可自行修改。\r\n"); - build.Append("* " + tableName + ".cs\r\n"); - build.Append("*\r\n"); - build.Append("*功 能: N / A\r\n"); - build.Append("* 类 名: " + tableName + "\r\n"); - build.Append("*\r\n"); - build.Append("* Ver 变更日期 负责人 变更内容\r\n"); - build.Append("* ───────────────────────────────────\r\n"); - build.Append("*V0.01 " + DateTime.Now.ToString() + " SimonHsiao 初版\r\n"); - build.Append("*\r\n"); - build.Append("* Copyright(c) " + DateTime.Now.Year + " Tiobon Corporation. All Rights Reserved.\r\n"); - build.Append("*┌──────────────────────────────────┐\r\n"); - build.Append("*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │\r\n"); - build.Append("*│ 作者:SimonHsiao │\r\n"); - build.Append("*└──────────────────────────────────┘\r\n"); - build.Append("*/ \r\n"); - build.Append("\r\n"); - build.Append("namespace Tiobon.Core.Model.Models\r\n"); - build.Append("{\r\n"); - build.Append("\r\n"); - build.Append(" /// \r\n"); - build.Append(" /// " + TableCnName + " (Dto.InsertInput)\r\n"); - build.Append(" /// \r\n"); - build.Append(" public class Insert" + tableName + "Input : " + tableName + "Base\r\n"); - build.Append(" {\r\n"); - - build.Append(" }\r\n"); - build.Append("}\r\n"); - - ls.Add(tableName + ".Dto.InsertInput", build.ToString()); - CreateFilesByClassStringList(ls, strPath + @"\Insert\" + groupName, "{0}"); - #endregion - - #region Edit - build = new StringBuilder(); - ls = new Dictionary(); - - build.Append("/* 代码由框架生成,任何更改都可能导致被代码生成器覆盖,可自行修改。\r\n"); - build.Append("* " + tableName + ".cs\r\n"); - build.Append("*\r\n"); - build.Append("*功 能: N / A\r\n"); - build.Append("* 类 名: " + tableName + "\r\n"); - build.Append("*\r\n"); - build.Append("* Ver 变更日期 负责人 变更内容\r\n"); - build.Append("* ───────────────────────────────────\r\n"); - build.Append("*V0.01 " + DateTime.Now.ToString() + " SimonHsiao 初版\r\n"); - build.Append("*\r\n"); - build.Append("* Copyright(c) " + DateTime.Now.Year + " Tiobon Corporation. All Rights Reserved.\r\n"); - build.Append("*┌──────────────────────────────────┐\r\n"); - build.Append("*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │\r\n"); - build.Append("*│ 作者:SimonHsiao │\r\n"); - build.Append("*└──────────────────────────────────┘\r\n"); - build.Append("*/ \r\n"); - build.Append("\r\n"); - build.Append("namespace Tiobon.Core.Model.Models\r\n"); - build.Append("{\r\n"); - build.Append("\r\n"); - build.Append(" /// \r\n"); - build.Append(" /// " + TableCnName + " (Dto.EditInput)\r\n"); - build.Append(" /// \r\n"); - build.Append(" public class Edit" + tableName + "Input : " + tableName + "Base\r\n"); - build.Append(" {\r\n"); - - build.Append(" }\r\n"); - build.Append("}\r\n"); - - ls.Add(tableName + ".Dto.EditInput", build.ToString()); - CreateFilesByClassStringList(ls, strPath + @"\Edit\" + groupName, "{0}"); - #endregion - - #region View - build = new StringBuilder(); - ls = new Dictionary(); - - build.Append("/* 代码由框架生成,任何更改都可能导致被代码生成器覆盖,可自行修改。\r\n"); - build.Append("* " + tableName + ".cs\r\n"); - build.Append("*\r\n"); - build.Append("*功 能: N / A\r\n"); - build.Append("* 类 名: " + tableName + "\r\n"); - build.Append("*\r\n"); - build.Append("* Ver 变更日期 负责人 变更内容\r\n"); - build.Append("* ───────────────────────────────────\r\n"); - build.Append("*V0.01 " + DateTime.Now.ToString() + " SimonHsiao 初版\r\n"); - build.Append("*\r\n"); - build.Append("* Copyright(c) " + DateTime.Now.Year + " Tiobon Corporation. All Rights Reserved.\r\n"); - build.Append("*┌──────────────────────────────────┐\r\n"); - build.Append("*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │\r\n"); - build.Append("*│ 作者:SimonHsiao │\r\n"); - build.Append("*└──────────────────────────────────┘\r\n"); - build.Append("*/ \r\n"); - build.Append("\r\n"); - build.Append("namespace Tiobon.Core.Model.Models;\r\n"); - build.Append("\r\n"); - build.Append("/// \r\n"); - build.Append("/// " + TableCnName + "(Dto.View1)\r\n"); - build.Append("/// \r\n"); - build.Append("public class " + tableName + "Dto : " + tableName + "\r\n"); - build.Append("{\r\n"); - - build.Append("/// \r\n"); - build.Append("/// 创建信息\r\n"); - build.Append("/// \r\n"); - build.Append("public string CreateDataInfo { get; set; }\r\n"); - build.Append("\r\n"); - - build.Append("/// \r\n"); - build.Append("/// 修改信息\r\n"); - build.Append("/// \r\n"); - build.Append("public string UpdateDataInfo { get; set; }\r\n"); - - build.Append("}\r\n"); - - ls.Add(tableName + ".Dto.View", build.ToString()); - CreateFilesByClassStringList(ls, strPath + @"\View\" + groupName, "{0}"); - #endregion - - } - #endregion - - - #region 根据数据库表生产IRepository层 - - /// - /// 根据数据库表生产IRepository层 - /// - /// - /// 数据库链接ID - /// 实体类存放路径 - /// 命名空间 - /// 生产指定的表 - /// 实现接口 - /// - private static void Create_IRepository_ClassFileByDBTalbe( - SqlSugarScope sqlSugarClient, - string ConnId, - string strPath, - string strNameSpace, - string[] lstTableNames, - string strInterface, - bool isMuti = false - ) - { - //多库文件分离 - if (isMuti) - { - strPath = strPath + @"\" + ConnId; - strNameSpace = strNameSpace + "." + ConnId; - } - - var IDbFirst = sqlSugarClient.DbFirst; - if (lstTableNames != null && lstTableNames.Length > 0) - { - IDbFirst = IDbFirst.Where(lstTableNames); - } - var ls = IDbFirst.IsCreateDefaultValue().IsCreateAttribute() - - .SettingClassTemplate(p => p = -@"using Tiobon.Core.IRepository.Base; -using Tiobon.Core.Model.Models" + (isMuti ? "." + ConnId + "" : "") + @"; - -namespace " + strNameSpace + @" -{ - /// - /// I{ClassName}Repository - /// - public interface I{ClassName}Repository : IBaseRepository<{ClassName}>" + (string.IsNullOrEmpty(strInterface) ? "" : (" , " + strInterface)) + @" - { - } -}") - - .ToClassStringList(strNameSpace); - CreateFilesByClassStringList(ls, strPath, "I{0}Repository"); - } - #endregion - - - #region 根据数据库表生产IServices层 - - /// - /// 根据数据库表生产IServices层 - /// - /// - /// 数据库链接ID - /// 实体类存放路径 - /// 命名空间 - /// 生产指定的表 - /// 实现接口 - /// - private static void Create_IServices_ClassFileByDBTalbe( - SqlSugarScope sqlSugarClient, - string ConnId, - string strPath, - string strNameSpace, - string[] lstTableNames, - string strInterface, - bool isMuti = false) - { - //多库文件分离 - if (isMuti) - { - strPath = strPath + @"\" + ConnId; - strNameSpace = strNameSpace + "." + ConnId; - } - - var IDbFirst = sqlSugarClient.DbFirst; - if (lstTableNames != null && lstTableNames.Length > 0) - { - IDbFirst = IDbFirst.Where(lstTableNames); - } - - var groupName = lstTableNames[0].Split('_')[0]; - - #region 获取表中文名 - string sql = @"SELECT f.value TableName - FROM sysobjects d - LEFT JOIN sys.extended_properties f - ON d.id = f.major_id AND f.minor_id = 0 - WHERE d.name = '{0}'"; - sql = string.Format(sql, lstTableNames[0]); - string TableCnName = Convert.ToString(DbAccess.ExecuteScalar(sql, null)); - if (string.IsNullOrWhiteSpace(TableCnName)) TableCnName = lstTableNames[0]; - #endregion - var ls = IDbFirst.IsCreateDefaultValue().IsCreateAttribute() - - .SettingClassTemplate(p => p = -@"using Tiobon.Core.Model.Models" + (isMuti ? "." + ConnId + "" : "") + @"; - -namespace " + strNameSpace + @" -{ - /// - /// " + TableCnName + @"(自定义服务接口) - /// - public interface I{ClassName}Services :IBaseServices<{ClassName}, {ClassName}Dto, Insert{ClassName}Input, Edit{ClassName}Input>" + (string.IsNullOrEmpty(strInterface) ? "" : (" , " + strInterface)) + @" - { - } -}") - - .ToClassStringList(strNameSpace); - CreateFilesByClassStringList(ls, strPath + "/" + groupName, "I{0}Services"); - } - #endregion - - - - #region 根据数据库表生产 Repository 层 - - /// - /// 根据数据库表生产 Repository 层 - /// - /// - /// 数据库链接ID - /// 实体类存放路径 - /// 命名空间 - /// 生产指定的表 - /// 实现接口 - /// - private static void Create_Repository_ClassFileByDBTalbe( - SqlSugarScope sqlSugarClient, - string ConnId, - string strPath, - string strNameSpace, - string[] lstTableNames, - string strInterface, - bool isMuti = false) - { - //多库文件分离 - if (isMuti) - { - strPath = strPath + @"\" + ConnId; - strNameSpace = strNameSpace + "." + ConnId; - } - - var IDbFirst = sqlSugarClient.DbFirst; - if (lstTableNames != null && lstTableNames.Length > 0) - { - IDbFirst = IDbFirst.Where(lstTableNames); - } - - #region 获取表中文名 - string sql = @"SELECT f.value TableName - FROM sysobjects d - LEFT JOIN sys.extended_properties f - ON d.id = f.major_id AND f.minor_id = 0 - WHERE d.name = '{0}'"; - sql = string.Format(sql, lstTableNames[0]); - string TableCnName = Convert.ToString(DbAccess.ExecuteScalar(sql, null)); - if (string.IsNullOrWhiteSpace(TableCnName)) TableCnName = lstTableNames[0]; - #endregion - - var ls = IDbFirst.IsCreateDefaultValue().IsCreateAttribute() - - .SettingClassTemplate(p => p = -@"using Tiobon.Core.IRepository" + (isMuti ? "." + ConnId + "" : "") + @"; -using Tiobon.Core.IRepository.UnitOfWork; -using Tiobon.Core.Model.Models" + (isMuti ? "." + ConnId + "" : "") + @"; -using Tiobon.Core.Repository.Base; - -namespace " + strNameSpace + @" -{ - /// - /// " + TableCnName + @"Repository - /// - public class {ClassName}Repository : BaseRepository<{ClassName}>, I{ClassName}Repository" + (string.IsNullOrEmpty(strInterface) ? "" : (" , " + strInterface)) + @" - { - public {ClassName}Repository(IUnitOfWork unitOfWork) : base(unitOfWork) - { - } - } -}") - .ToClassStringList(strNameSpace); - - - CreateFilesByClassStringList(ls, strPath, "{0}Repository"); - } - #endregion - - - #region 根据数据库表生产 Services 层 - - /// - /// 根据数据库表生产 Services 层 - /// - /// - /// 数据库链接ID - /// 实体类存放路径 - /// 命名空间 - /// 生产指定的表 - /// 实现接口 - /// - private static void Create_Services_ClassFileByDBTalbe( - SqlSugarScope sqlSugarClient, - string ConnId, - string strPath, - string strNameSpace, - string[] lstTableNames, - string strInterface, - bool isMuti = false) - { - //多库文件分离 - if (isMuti) - { - strPath = strPath + @"\" + ConnId; - strNameSpace = strNameSpace + "." + ConnId; - } - - var IDbFirst = sqlSugarClient.DbFirst; - if (lstTableNames != null && lstTableNames.Length > 0) - { - IDbFirst = IDbFirst.Where(lstTableNames); - } - - #region 获取表中文名 - string sql = @"SELECT f.value TableName - FROM sysobjects d - LEFT JOIN sys.extended_properties f - ON d.id = f.major_id AND f.minor_id = 0 - WHERE d.name = '{0}'"; - sql = string.Format(sql, lstTableNames[0]); - string TableCnName = Convert.ToString(DbAccess.ExecuteScalar(sql, null)); - if (string.IsNullOrWhiteSpace(TableCnName)) TableCnName = lstTableNames[0]; - #endregion - var groupName = lstTableNames[0].Split('_')[0]; - - var ls = IDbFirst.IsCreateDefaultValue().IsCreateAttribute() - - .SettingClassTemplate(p => p = -@" -using Tiobon.Core.IServices" + (isMuti ? "." + ConnId + "" : "") + @"; -using Tiobon.Core.Model.Models" + (isMuti ? "." + ConnId + "" : "") + @"; -using Tiobon.Core.Services.BASE; -using Tiobon.Core.IRepository.Base; -using Tiobon.Core.Common.Caches; - -namespace " + strNameSpace + @" -{ - /// - /// " + TableCnName + @" (服务) - /// - public class {ClassName}Services : BaseServices<{ClassName}, {ClassName}Dto, Insert{ClassName}Input, Edit{ClassName}Input>, I{ClassName}Services" + (string.IsNullOrEmpty(strInterface) ? "" : (" , " + strInterface)) + @" - { - private readonly IBaseRepository<{ClassName}> _dal; - public {ClassName}Services(ICaching caching, IBaseRepository<{ClassName}> dal) - { - this._dal = dal; - base.BaseDal = dal; - base._caching = caching; - } - } -}") - .ToClassStringList(strNameSpace); - - CreateFilesByClassStringList(ls, strPath + "/" + groupName, "{0}Services"); - } - #endregion - - - #region 根据模板内容批量生成文件 - /// - /// 根据模板内容批量生成文件 - /// - /// 类文件字符串list - /// 生成路径 - /// 文件名格式模板 - private static void CreateFilesByClassStringList(Dictionary ls, string strPath, string fileNameTp) - { - - foreach (var item in ls) - { - var fileName = $"{string.Format(fileNameTp, item.Key)}.cs"; - var fileFullPath = Path.Combine(strPath, fileName); - if (!Directory.Exists(strPath)) - { - Directory.CreateDirectory(strPath); - } - File.WriteAllText(fileFullPath, item.Value, Encoding.UTF8); - } - } - #endregion -} diff --git a/Tiobon.Core.Common/Seed/IEntitySeedData.cs b/Tiobon.Core.Common/Seed/IEntitySeedData.cs deleted file mode 100644 index 61e7492c..00000000 --- a/Tiobon.Core.Common/Seed/IEntitySeedData.cs +++ /dev/null @@ -1,34 +0,0 @@ -using SqlSugar; - -namespace Tiobon.Core.Common.Seed; - -/// -/// 种子数据 接口 -/// -/// -public interface IEntitySeedData - where T : class, new() -{ - /// - /// 初始化种子数据
- /// 只要表不存在数据,程序启动就会自动初始化 - ///
- /// - IEnumerable InitSeedData(); - - /// - /// 种子数据
- /// 存在不操作、不存在Insert
- /// 适合系统内置数据,项目开发后续增加内置数据 - ///
- /// - IEnumerable SeedData(); - - /// - /// 自定义操作
- /// 以上满不足了,可以自己编写 - ///
- /// - /// - Task CustomizeSeedData(ISqlSugarClient db); -} \ No newline at end of file diff --git a/Tiobon.Core.Common/Seed/MyContext.cs b/Tiobon.Core.Common/Seed/MyContext.cs deleted file mode 100644 index c87e3868..00000000 --- a/Tiobon.Core.Common/Seed/MyContext.cs +++ /dev/null @@ -1,225 +0,0 @@ -using SqlSugar; -using Tiobon.Core.DB; - -namespace Tiobon.Core.Common.Seed; - -public class MyContext -{ - - private static MutiDBOperate connectObject => GetMainConnectionDb(); - private static string _connectionString = connectObject.Connection; - private static DbType _dbType = (DbType)connectObject.DbType; - public static string ConnId = connectObject.ConnId; - private SqlSugarScope _db; - - /// - /// 连接字符串 - /// Tiobon.Core - /// - public static MutiDBOperate GetMainConnectionDb() - { - var mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId); - if (BaseDBConfig.MutiConnectionString.allDbs.Count > 0) - { - if (mainConnetctDb == null) - { - mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs[0]; - } - } - else - { - throw new Exception("请确保appsettigns.json中配置连接字符串,并设置Enabled为true;"); - } - - return mainConnetctDb; - } - /// - /// 连接字符串 - /// Tiobon.Core - /// - public static string ConnectionString - { - get { return _connectionString; } - set { _connectionString = value; } - } - /// - /// 数据库类型 - /// Tiobon.Core - /// - public static DbType DbType - { - get { return _dbType; } - set { _dbType = value; } - } - /// - /// 数据连接对象 - /// Tiobon.Core - /// - public SqlSugarScope Db - { - get { return _db; } - private set { _db = value; } - } - - /// - /// 功能描述:构造函数 - /// 作  者:Tiobon.Core - /// - public MyContext(ISqlSugarClient sqlSugarClient) - { - if (string.IsNullOrEmpty(_connectionString)) - throw new ArgumentNullException("数据库连接字符串为空"); - - _db = sqlSugarClient as SqlSugarScope; - - } - - - #region 实例方法 - /// - /// 功能描述:获取数据库处理对象 - /// 作  者:Tiobon.Core - /// - /// 返回值 - public SimpleClient GetEntityDB() where T : class, new() - { - return new SimpleClient(_db); - } - /// - /// 功能描述:获取数据库处理对象 - /// 作  者:Tiobon.Core - /// - /// db - /// 返回值 - //public SimpleClient GetEntityDB(SqlSugarClient db) where T : class, new() - //{ - // return new SimpleClient(db); - //} - - - - #endregion - - - #region 根据实体类生成数据库表 - /// - /// 功能描述:根据实体类生成数据库表 - /// 作  者:Tiobon.Core - /// - /// 是否备份表 - /// 指定的实体 - public void CreateTableByEntity(bool blnBackupTable, params T[] lstEntitys) where T : class, new() - { - Type[] lstTypes = null; - if (lstEntitys != null) - { - lstTypes = new Type[lstEntitys.Length]; - for (int i = 0; i < lstEntitys.Length; i++) - { - T t = lstEntitys[i]; - lstTypes[i] = typeof(T); - } - } - CreateTableByEntity(blnBackupTable, lstTypes); - } - - /// - /// 功能描述:根据实体类生成数据库表 - /// 作  者:Tiobon.Core - /// - /// 是否备份表 - /// 指定的实体 - public void CreateTableByEntity(bool blnBackupTable, params Type[] lstEntitys) - { - if (blnBackupTable) - { - _db.CodeFirst.BackupTable().InitTables(lstEntitys); //change entity backupTable - } - else - { - _db.CodeFirst.InitTables(lstEntitys); - } - } - #endregion - - - #region 静态方法 - - ///// - ///// 功能描述:获得一个DbContext - ///// 作  者:Tiobon.Core - ///// - ///// - //public static MyContext GetDbContext() - //{ - // return new MyContext(); - //} - - /// - /// 功能描述:设置初始化参数 - /// 作  者:Tiobon.Core - /// - /// 连接字符串 - /// 数据库类型 - public static void Init(string strConnectionString, DbType enmDbType = SqlSugar.DbType.SqlServer) - { - _connectionString = strConnectionString; - _dbType = enmDbType; - } - - /// - /// 功能描述:创建一个链接配置 - /// 作  者:Tiobon.Core - /// - /// 是否自动关闭连接 - /// 是否夸类事务 - /// ConnectionConfig - public static ConnectionConfig GetConnectionConfig(bool blnIsAutoCloseConnection = true, bool blnIsShardSameThread = false) - { - ConnectionConfig config = new ConnectionConfig() - { - ConnectionString = _connectionString, - DbType = _dbType, - IsAutoCloseConnection = blnIsAutoCloseConnection, - ConfigureExternalServices = new ConfigureExternalServices() - { - //DataInfoCacheService = new HttpRuntimeCache() - }, - //IsShardSameThread = blnIsShardSameThread - }; - return config; - } - - /// - /// 功能描述:获取一个自定义的DB - /// 作  者:Tiobon.Core - /// - /// config - /// 返回值 - public static SqlSugarScope GetCustomDB(ConnectionConfig config) - { - return new SqlSugarScope(config); - } - /// - /// 功能描述:获取一个自定义的数据库处理对象 - /// 作  者:Tiobon.Core - /// - /// sugarClient - /// 返回值 - public static SimpleClient GetCustomEntityDB(SqlSugarScope sugarClient) where T : class, new() - { - return new SimpleClient(sugarClient); - } - /// - /// 功能描述:获取一个自定义的数据库处理对象 - /// 作  者:Tiobon.Core - /// - /// config - /// 返回值 - public static SimpleClient GetCustomEntityDB(ConnectionConfig config) where T : class, new() - { - SqlSugarScope sugarClient = GetCustomDB(config); - return GetCustomEntityDB(sugarClient); - } - #endregion -} diff --git a/Tiobon.Core.Common/Seed/SeedData/BusinessDataSeedData.cs b/Tiobon.Core.Common/Seed/SeedData/BusinessDataSeedData.cs deleted file mode 100644 index ddcf1fac..00000000 --- a/Tiobon.Core.Common/Seed/SeedData/BusinessDataSeedData.cs +++ /dev/null @@ -1,77 +0,0 @@ -using SqlSugar; -using Tiobon.Core.Model.Models; - -namespace Tiobon.Core.Common.Seed.SeedData; - -/// -/// 初始化 业务数据 -/// -public class BusinessDataSeedData : IEntitySeedData -{ - public IEnumerable InitSeedData() - { - return new[] - { - new BusinessTable() - { - Id = 1, - TenantId = 1000001, - Name = "张三的数据01", - Amount = 150, - IsDeleted = true, - }, - new BusinessTable() - { - Id = 2, - TenantId = 1000001, - Name = "张三的数据02", - Amount = 200, - }, - new BusinessTable() - { - Id = 3, - TenantId = 1000001, - Name = "张三的数据03", - Amount = 250, - }, - new BusinessTable() - { - Id = 4, - TenantId = 1000002, - Name = "李四的数据01", - Amount = 300, - }, - new BusinessTable() - { - Id = 5, - TenantId = 1000002, - Name = "李四的数据02", - Amount = 500, - }, - new BusinessTable() - { - Id = 6, - TenantId = 0, - Name = "公共数据01", - Amount = 16600, - }, - new BusinessTable() - { - Id = 7, - TenantId = 0, - Name = "公共数据02", - Amount = 19800, - }, - }; - } - - public IEnumerable SeedData() - { - return default; - } - - public Task CustomizeSeedData(ISqlSugarClient db) - { - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/Tiobon.Core.Common/Seed/SeedData/MultiBusinessDataSeedData.cs b/Tiobon.Core.Common/Seed/SeedData/MultiBusinessDataSeedData.cs deleted file mode 100644 index c6d51548..00000000 --- a/Tiobon.Core.Common/Seed/SeedData/MultiBusinessDataSeedData.cs +++ /dev/null @@ -1,36 +0,0 @@ -using SqlSugar; -using Tiobon.Core.Model.Models; - -namespace Tiobon.Core.Common.Seed.SeedData; - -public class MultiBusinessDataSeedData : IEntitySeedData -{ - public IEnumerable InitSeedData() - { - return new List() - { - new() - { - Id = 1001, - Name = "业务数据1", - Amount = 100, - }, - new() - { - Id = 1002, - Name = "业务数据2", - Amount = 1000, - }, - }; - } - - public IEnumerable SeedData() - { - return default; - } - - public Task CustomizeSeedData(ISqlSugarClient db) - { - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/Tiobon.Core.Common/Seed/SeedData/MultiBusinessSubDataSeedData.cs b/Tiobon.Core.Common/Seed/SeedData/MultiBusinessSubDataSeedData.cs deleted file mode 100644 index 2dc2a16d..00000000 --- a/Tiobon.Core.Common/Seed/SeedData/MultiBusinessSubDataSeedData.cs +++ /dev/null @@ -1,36 +0,0 @@ -using SqlSugar; -using Tiobon.Core.Model.Models; - -namespace Tiobon.Core.Common.Seed.SeedData; - -public class MultiBusinessSubDataSeedData : IEntitySeedData -{ - public IEnumerable InitSeedData() - { - return new List() - { - new() - { - Id = 100, - MainId = 1001, - Memo = "子数据", - }, - new() - { - Id = 1001, - MainId = 1001, - Memo = "子数据2", - }, - }; - } - - public IEnumerable SeedData() - { - return default; - } - - public Task CustomizeSeedData(ISqlSugarClient db) - { - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/Tiobon.Core.Common/Seed/SeedData/SubBusinessDataSeedData.cs b/Tiobon.Core.Common/Seed/SeedData/SubBusinessDataSeedData.cs deleted file mode 100644 index 21e9c6d4..00000000 --- a/Tiobon.Core.Common/Seed/SeedData/SubBusinessDataSeedData.cs +++ /dev/null @@ -1,68 +0,0 @@ -using SqlSugar; -using Tiobon.Core.Model.Models; - -namespace Tiobon.Core.Common.Seed.SeedData; - -public class SubBusinessDataSeedData : IEntitySeedData -{ - public IEnumerable InitSeedData() - { - return default; - } - - public IEnumerable SeedData() - { - return default; - } - - public async Task CustomizeSeedData(ISqlSugarClient db) - { - //初始化分库数据 - //只是用于测试 - if (db.CurrentConnectionConfig.ConfigId == "Tenant_3") - { - if (!await db.Queryable().AnyAsync()) - { - await db.Insertable(new List() - { - new() - { - Id = SnowFlakeSingle.Instance.NextId(), - Name = "王五业务数据1", - Amount = 100, - }, - new() - { - Id = SnowFlakeSingle.Instance.NextId(), - Name = "王五业务数据2", - Amount = 1000, - }, - }).ExecuteReturnSnowflakeIdListAsync(); - } - } - else if (db.CurrentConnectionConfig.ConfigId == "Tenant_4") - { - if (!await db.Queryable().AnyAsync()) - { - await db.Insertable(new List() - { - new() - { - Id = SnowFlakeSingle.Instance.NextId(), - Name = "赵六业务数据1", - Amount = 50, - }, - new() - { - Id = SnowFlakeSingle.Instance.NextId(), - Name = "赵六业务数据2", - Amount = 60, - }, - }).ExecuteReturnSnowflakeIdListAsync(); - } - } - - - await Task.Delay(1); - } -} \ No newline at end of file diff --git a/Tiobon.Core.Common/Seed/SeedData/TenantSeedData.cs b/Tiobon.Core.Common/Seed/SeedData/TenantSeedData.cs deleted file mode 100644 index 92d17e9b..00000000 --- a/Tiobon.Core.Common/Seed/SeedData/TenantSeedData.cs +++ /dev/null @@ -1,66 +0,0 @@ -using SqlSugar; -using Tiobon.Core.Model; - -namespace Tiobon.Core.Common.Seed.SeedData; - -/// -/// 租户 种子数据 -/// -public class TenantSeedData : IEntitySeedData -{ - public IEnumerable InitSeedData() - { - return new[] - { - new SysTenant() - { - Id = 1000001, - ConfigId = "Tenant_1", - Name = "张三", - TenantType = TenantTypeEnum.Id - }, - new SysTenant() - { - Id = 1000002, - ConfigId = "Tenant_2", - Name = "李四", - TenantType = TenantTypeEnum.Id - }, - new SysTenant() - { - Id = 1000003, - ConfigId = "Tenant_3", - Name = "王五", - TenantType = TenantTypeEnum.Db, - DbType = DbType.Sqlite, - Connection = $"DataSource=" + Path.Combine(Environment.CurrentDirectory, "WangWu.db"), - }, - new SysTenant() - { - Id = 1000004, - ConfigId = "Tenant_4", - Name = "赵六", - TenantType = TenantTypeEnum.Db, - DbType = DbType.Sqlite, - Connection = $"DataSource=" + Path.Combine(Environment.CurrentDirectory, "ZhaoLiu.db"), - }, - new SysTenant() - { - Id = 1000005, - ConfigId = "Tenant_5", - Name = "孙七", - TenantType = TenantTypeEnum.Tables, - }, - }; - } - - public IEnumerable SeedData() - { - return default; - } - - public Task CustomizeSeedData(ISqlSugarClient db) - { - return Task.CompletedTask; - } -} \ No newline at end of file diff --git a/Tiobon.Core.Common/Seed/SeedData/UserInfoSeedData.cs b/Tiobon.Core.Common/Seed/SeedData/UserInfoSeedData.cs deleted file mode 100644 index 0512612d..00000000 --- a/Tiobon.Core.Common/Seed/SeedData/UserInfoSeedData.cs +++ /dev/null @@ -1,77 +0,0 @@ -using SqlSugar; -using Tiobon.Core.Model.Models; - -namespace Tiobon.Core.Common.Seed.SeedData; - -public class UserInfoSeedData : IEntitySeedData -{ - public IEnumerable InitSeedData() - { - return default; - } - - public IEnumerable SeedData() - { - return default; - } - - public async Task CustomizeSeedData(ISqlSugarClient db) - { - var data = new List() - { - new SysUserInfo() - { - Id = 10001, - LoginName = "zhangsan", - LoginPWD = "E10ADC3949BA59ABBE56E057F20F883E", - Name = "张三", - TenantId = 1000001, //租户Id - }, - new SysUserInfo() - { - Id = 10002, - LoginName = "lisi", - LoginPWD = "E10ADC3949BA59ABBE56E057F20F883E", - Name = "李四", - TenantId = 1000002, //租户Id - }, - new SysUserInfo() - { - Id = 10003, - LoginName = "wangwu", - LoginPWD = "E10ADC3949BA59ABBE56E057F20F883E", - Name = "王五", - TenantId = 1000003, //租户Id - }, - new SysUserInfo() - { - Id = 10004, - LoginName = "zhaoliu", - LoginPWD = "E10ADC3949BA59ABBE56E057F20F883E", - Name = "赵六", - TenantId = 1000004, //租户Id - }, - new SysUserInfo() - { - Id = 10005, - LoginName = "sunqi", - LoginPWD = "E10ADC3949BA59ABBE56E057F20F883E", - Name = "孙七", - TenantId = 1000005, //租户Id - }, - }; - - var names = data.Select(s => s.LoginName).ToList(); - names = await db.Queryable() - .Where(s => names.Contains(s.LoginName)) - .Select(s => s.LoginName).ToListAsync(); - - var sysUserInfos = data.Where(s => !names.Contains(s.LoginName)).ToList(); - if (sysUserInfos.Any()) - { - await db.Insertable(sysUserInfos).ExecuteReturnIdentityAsync(); - } - - await Task.CompletedTask; - } -} \ No newline at end of file diff --git a/Tiobon.Core.Extensions/AutoMapper/CustomProfile.cs b/Tiobon.Core.Extensions/AutoMapper/CustomProfile.cs index 8fa5deff..7913420f 100644 --- a/Tiobon.Core.Extensions/AutoMapper/CustomProfile.cs +++ b/Tiobon.Core.Extensions/AutoMapper/CustomProfile.cs @@ -1,4 +1,5 @@ using AutoMapper; +using Tiobon.Core.Model; using Tiobon.Core.Model.Models; using Tiobon.Core.Model.ViewModels; diff --git a/Tiobon.Core.Extensions/HostedService/SeedDataHostedService.cs b/Tiobon.Core.Extensions/HostedService/SeedDataHostedService.cs index 0d97548c..475a050a 100644 --- a/Tiobon.Core.Extensions/HostedService/SeedDataHostedService.cs +++ b/Tiobon.Core.Extensions/HostedService/SeedDataHostedService.cs @@ -1,8 +1,7 @@ using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Tiobon.Core.Common; -using Tiobon.Core.Common.Seed; +using Tiobon.Core.Seed; namespace Tiobon.Core.Extensions; diff --git a/Tiobon.Core.Extensions/ServiceExtensions/DbSetup.cs b/Tiobon.Core.Extensions/ServiceExtensions/DbSetup.cs index 9a31ef0c..4c746db8 100644 --- a/Tiobon.Core.Extensions/ServiceExtensions/DbSetup.cs +++ b/Tiobon.Core.Extensions/ServiceExtensions/DbSetup.cs @@ -1,5 +1,5 @@ using Microsoft.Extensions.DependencyInjection; -using Tiobon.Core.Common.Seed; +using Tiobon.Core.Seed; namespace Tiobon.Core.Extensions; diff --git a/Tiobon.Core.Jobs/Helper.cs b/Tiobon.Core.Jobs/Helper.cs index b9802617..53a1bf93 100644 --- a/Tiobon.Core.Jobs/Helper.cs +++ b/Tiobon.Core.Jobs/Helper.cs @@ -3,7 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; -using Tiobon.Core.Common.Seed; +using Tiobon.Core.Seed; using Tiobon.Core.DataAccess; using Tiobon.Core.DB; using Tiobon.Core.DB.Dapper.Extensions; diff --git a/Tiobon.Core.Model/Models/RootTkey/sysUserInfoRoot.cs b/Tiobon.Core.Model/Models/RootTkey/sysUserInfoRoot.cs deleted file mode 100644 index 19109317..00000000 --- a/Tiobon.Core.Model/Models/RootTkey/sysUserInfoRoot.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace Tiobon.Core.Model; - -/// -/// 用户信息表 -/// -public class SysUserInfoRoot where Tkey : IEquatable -{ - /// - /// Id - /// 泛型主键Tkey - /// - [SugarColumn(IsNullable = false, IsPrimaryKey = true)] - public Tkey Id { get; set; } - - [SugarColumn(IsIgnore = true)] - public List RIDs { get; set; } - -} diff --git a/Tiobon.Core.Model/Models/Tenant/BusinessTable.cs b/Tiobon.Core.Model/Models/Tenant/BusinessTable.cs deleted file mode 100644 index 70646cc9..00000000 --- a/Tiobon.Core.Model/Models/Tenant/BusinessTable.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Tiobon.Core.Model.Tenants; - -namespace Tiobon.Core.Model.Models; - -/// -/// 业务数据
-/// 多租户 (Id 隔离) -///
-public class BusinessTable : BaseEntity, ITenantEntity -{ - /// - /// 无需手动赋值 - /// - public long TenantId { get; set; } - - - /// - /// 名称 - /// - public string Name { get; set; } - - /// - /// 金额 - /// - public decimal Amount { get; set; } -} \ No newline at end of file diff --git a/Tiobon.Core.Model/Models/Tenant/MultiBusinessSubTable.cs b/Tiobon.Core.Model/Models/Tenant/MultiBusinessSubTable.cs deleted file mode 100644 index 8c86cecf..00000000 --- a/Tiobon.Core.Model/Models/Tenant/MultiBusinessSubTable.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Tiobon.Core.Model.Models; - -/// -/// 多租户-多表方案 业务表 子表
-///
-[MultiTenant(TenantTypeEnum.Tables)] -public class MultiBusinessSubTable : BaseEntity -{ - public long MainId { get; set; } - public string Memo { get; set; } -} \ No newline at end of file diff --git a/Tiobon.Core.Model/Models/Tenant/MultiBusinessTable.cs b/Tiobon.Core.Model/Models/Tenant/MultiBusinessTable.cs deleted file mode 100644 index 46b1f903..00000000 --- a/Tiobon.Core.Model/Models/Tenant/MultiBusinessTable.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace Tiobon.Core.Model.Models; - -/// -/// 多租户-多表方案 业务表
-///
-[MultiTenant(TenantTypeEnum.Tables)] -public class MultiBusinessTable : BaseEntity -{ - /// - /// 名称 - /// - public string Name { get; set; } - - /// - /// 金额 - /// - public decimal Amount { get; set; } - - [Navigate(NavigateType.OneToMany, nameof(MultiBusinessSubTable.MainId))] - public List Child { get; set; } -} \ No newline at end of file diff --git a/Tiobon.Core.Model/Models/Tenant/SubLibraryBusinessTable.cs b/Tiobon.Core.Model/Models/Tenant/SubLibraryBusinessTable.cs deleted file mode 100644 index 075e782d..00000000 --- a/Tiobon.Core.Model/Models/Tenant/SubLibraryBusinessTable.cs +++ /dev/null @@ -1,19 +0,0 @@ -namespace Tiobon.Core.Model.Models; - -/// -/// 多租户-多库方案 业务表
-/// 公共库无需标记[MultiTenant]特性 -///
-[MultiTenant] -public class SubLibraryBusinessTable : BaseEntity -{ - /// - /// 名称 - /// - public string Name { get; set; } - - /// - /// 金额 - /// - public decimal Amount { get; set; } -} \ No newline at end of file diff --git a/Tiobon.Core.Model/Models/sysUserInfo.cs b/Tiobon.Core.Model/Models/sysUserInfo.cs deleted file mode 100644 index 2aa44b78..00000000 --- a/Tiobon.Core.Model/Models/sysUserInfo.cs +++ /dev/null @@ -1,139 +0,0 @@ -namespace Tiobon.Core.Model.Models; - -/// -/// 用户信息表 -/// -//[SugarTable("SysUserInfo")] -[SugarTable("SysUserInfo", "用户表")] //('数据库表名','数据库表备注') -public class SysUserInfo : SysUserInfoRoot -{ - public SysUserInfo() - { - } - - public SysUserInfo(string loginName, string loginPWD) - { - LoginName = loginName; - LoginPWD = loginPWD; - RealName = LoginName; - Status = 0; - CreateTime = DateTime.Now; - UpdateTime = DateTime.Now; - LastErrorTime = DateTime.Now; - ErrorCount = 0; - Name = ""; - } - - /// - /// 登录账号 - /// - [SugarColumn(Length = 200, IsNullable = true, ColumnDescription = "登录账号")] - //:eg model 根据sqlsugar的完整定义可以如下定义,ColumnDescription可定义表字段备注 - //[SugarColumn(IsNullable = false, ColumnDescription = "登录账号", IsPrimaryKey = false, IsIdentity = false, Length = 50)] - //ColumnDescription 表字段备注, 已在MSSQL测试,配合 [SugarTable("SysUserInfo", "用户表")]//('数据库表名','数据库表备注') - //可以完整生成 表备注和各个字段的中文备注 - //2022/10/11 - //测试mssql 发现 不写ColumnDescription,写好注释在mssql下也能生成表字段备注 - public string LoginName { get; set; } - - /// - /// 登录密码 - /// - [SugarColumn(Length = 200, IsNullable = true)] - public string LoginPWD { get; set; } - - /// - /// 真实姓名 - /// - [SugarColumn(Length = 200, IsNullable = true)] - public string RealName { get; set; } - - /// - /// 状态 - /// - public int Status { get; set; } - - /// - /// 部门 - /// - [SugarColumn(IsNullable = true)] - public long DepartmentId { get; set; } = -1; - - /// - /// 备注 - /// - [SugarColumn(Length = 2000, IsNullable = true)] - public string Remark { get; set; } - - /// - /// 创建时间 - /// - public DateTime CreateTime { get; set; } = DateTime.Now; - - /// - /// 更新时间 - /// - public DateTime UpdateTime { get; set; } = DateTime.Now; - - /// - /// 关键业务修改时间 - /// - public DateTime CriticalModifyTime { get; set; } = DateTime.Now; - - /// - ///最后异常时间 - /// - public DateTime LastErrorTime { get; set; } = DateTime.Now; - - /// - ///错误次数 - /// - public int ErrorCount { get; set; } - - - /// - /// 登录账号 - /// - [SugarColumn(Length = 200, IsNullable = true)] - public string Name { get; set; } - - // 性别 - [SugarColumn(IsNullable = true)] - public int Sex { get; set; } = 0; - - // 年龄 - [SugarColumn(IsNullable = true)] - public int Age { get; set; } - - // 生日 - [SugarColumn(IsNullable = true)] - public DateTime Birth { get; set; } = DateTime.Now; - - // 地址 - [SugarColumn(Length = 200, IsNullable = true)] - public string Address { get; set; } - - [SugarColumn(DefaultValue = "1")] - public bool Enable { get; set; } = true; - - [SugarColumn(IsNullable = true)] - public bool IsDeleted { get; set; } - - /// - /// 租户Id - /// - [SugarColumn(IsNullable = false, DefaultValue = "0")] - public long TenantId { get; set; } - - [Navigate(NavigateType.OneToOne, nameof(TenantId))] - public SysTenant Tenant { get; set; } - - [SugarColumn(IsIgnore = true)] - public List RoleNames { get; set; } - - [SugarColumn(IsIgnore = true)] - public List Dids { get; set; } - - [SugarColumn(IsIgnore = true)] - public string DepartmentName { get; set; } -} diff --git a/Tiobon.Core.Model/ViewModels/RootTKey/SysUserInfoDtoRoot.cs b/Tiobon.Core.Model/ViewModels/RootTKey/SysUserInfoDtoRoot.cs deleted file mode 100644 index 48a5c14c..00000000 --- a/Tiobon.Core.Model/ViewModels/RootTKey/SysUserInfoDtoRoot.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace Tiobon.Core.Model.ViewModels -{ - public class SysUserInfoDtoRoot where Tkey : IEquatable - { - public Tkey uID { get; set; } - - public List RIDs { get; set; } - - } -} diff --git a/Tiobon.Core.Model/ViewModels/SysUserInfoDto.cs b/Tiobon.Core.Model/ViewModels/SysUserInfoDto.cs deleted file mode 100644 index e740c3ff..00000000 --- a/Tiobon.Core.Model/ViewModels/SysUserInfoDto.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace Tiobon.Core.Model.ViewModels; - -public class SysUserInfoDto : SysUserInfoDtoRoot -{ - public string uLoginName { get; set; } - public string uLoginPWD { get; set; } - public string uRealName { get; set; } - public int uStatus { get; set; } - public long DepartmentId { get; set; } - public string uRemark { get; set; } - public System.DateTime uCreateTime { get; set; } = DateTime.Now; - public System.DateTime uUpdateTime { get; set; } = DateTime.Now; - public DateTime uLastErrTime { get; set; } = DateTime.Now; - public int uErrorCount { get; set; } - public string name { get; set; } - public int sex { get; set; } = 0; - public int age { get; set; } - public DateTime birth { get; set; } = DateTime.Now; - public string addr { get; set; } - public bool tdIsDelete { get; set; } - public List RoleNames { get; set; } - public List Dids { get; set; } - public string DepartmentName { get; set; } -} diff --git a/Tiobon.Core.Services/TenantService.cs b/Tiobon.Core.Services/TenantService.cs index 3c9783db..007a20d0 100644 --- a/Tiobon.Core.Services/TenantService.cs +++ b/Tiobon.Core.Services/TenantService.cs @@ -1,6 +1,5 @@ -using Tiobon.Core.Common.DB; -using Tiobon.Core.Common.Seed; -using Tiobon.Core.Repository.UnitOfWorks; +using Tiobon.Core.Repository.UnitOfWorks; +using Tiobon.Core.Seed; namespace Tiobon.Core.Services; diff --git a/Tiobon.Core.Tests/Common_Test/DynamicLambdaTest.cs b/Tiobon.Core.Tests/Common_Test/DynamicLambdaTest.cs index 43c003a1..a4b50b3f 100644 --- a/Tiobon.Core.Tests/Common_Test/DynamicLambdaTest.cs +++ b/Tiobon.Core.Tests/Common_Test/DynamicLambdaTest.cs @@ -2,6 +2,7 @@ using SqlSugar; using Tiobon.Core.Helper; using Tiobon.Core.IRepository.Base; +using Tiobon.Core.Model; using Tiobon.Core.Model.Models; using Xunit; using Xunit.Abstractions; diff --git a/Tiobon.Core.Tests/DependencyInjection/DI_Test.cs b/Tiobon.Core.Tests/DependencyInjection/DI_Test.cs index a0b3a2e8..89848c06 100644 --- a/Tiobon.Core.Tests/DependencyInjection/DI_Test.cs +++ b/Tiobon.Core.Tests/DependencyInjection/DI_Test.cs @@ -12,7 +12,7 @@ using System.Security.Claims; using System.Text; using Tiobon.Core.AuthHelper; using Tiobon.Core.AppConfig; -using Tiobon.Core.Common.Seed; +using Tiobon.Core.Seed; using Tiobon.Core.DB; using Tiobon.Core.Extensions; using Tiobon.Core.IRepository.Base; diff --git a/Tiobon.Core/Tiobon.Core.Model.xml b/Tiobon.Core/Tiobon.Core.Model.xml index df038433..2cd41bdf 100644 --- a/Tiobon.Core/Tiobon.Core.Model.xml +++ b/Tiobon.Core/Tiobon.Core.Model.xml @@ -39070,133 +39070,6 @@ 修改时间
- - - 用户信息表 - - - - - 登录账号 - - - - - 登录密码 - - - - - 真实姓名 - - - - - 状态 - - - - - 部门 - - - - - 备注 - - - - - 创建时间 - - - - - 更新时间 - - - - - 关键业务修改时间 - - - - - 最后异常时间 - - - - - 错误次数 - - - - - 登录账号 - - - - - 租户Id - - - - - 业务数据
- 多租户 (Id 隔离) -
-
- - - 无需手动赋值 - - - - - 名称 - - - - - 金额 - - - - - 多租户-多表方案 业务表 子表
-
-
- - - 多租户-多表方案 业务表
-
-
- - - 名称 - - - - - 金额 - - - - - 多租户-多库方案 业务表
- 公共库无需标记[MultiTenant]特性 -
-
- - - 名称 - - - - - 金额 - - 用户跟角色关联表 @@ -42761,17 +42634,6 @@ api ID - - - 用户信息表 - - - - - Id - 泛型主键Tkey - - 用户跟角色关联表