From 8478df3a1193805d2c904582da5e09c85ec77a1d Mon Sep 17 00:00:00 2001 From: izory <791736813@qq.com> Date: Wed, 8 Sep 2021 18:12:08 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0service=E3=80=81Repository=E3=80=81Controller=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/CodeGeneratorController.cs | 11 +- ZR.Admin.WebApi/Extensions/EntityExtension.cs | 12 +- .../Template/ControllersTemplate.txt | 124 +++++++ ZR.Admin.WebApi/Template/IServiceTemplate.txt | 13 + .../Template/RepositoryTemplate.txt | 24 ++ ZR.Admin.WebApi/Template/ServiceTemplate.txt | 28 ++ ZR.Admin.WebApi/Template/VueJsTemplate.txt | 85 +++++ ZR.Admin.WebApi/Template/VueTemplate.txt | 249 +++++++++++++ ZR.Admin.WebApi/ZR.Admin.WebApi.csproj | 28 ++ ZR.Admin.WebApi/appsettings.Production.json | 3 +- ZR.CodeGenerator/CodeGeneratorTool.cs | 330 +++++++++++++++--- ZR.CodeGenerator/DbProvider.cs | 21 +- .../Service/CodeGeneraterService.cs | 34 +- .../System/CodeGeneratorRepository.cs | 75 ---- ZR.Service/System/CodeGeneratorService.cs | 99 ------ ZR.Service/ZR.Service.csproj | 4 + ZR.Vue/src/views/tool/index.vue | 45 +-- 17 files changed, 897 insertions(+), 288 deletions(-) create mode 100644 ZR.Admin.WebApi/Template/ControllersTemplate.txt create mode 100644 ZR.Admin.WebApi/Template/IServiceTemplate.txt create mode 100644 ZR.Admin.WebApi/Template/RepositoryTemplate.txt create mode 100644 ZR.Admin.WebApi/Template/ServiceTemplate.txt create mode 100644 ZR.Admin.WebApi/Template/VueJsTemplate.txt create mode 100644 ZR.Admin.WebApi/Template/VueTemplate.txt delete mode 100644 ZR.Repository/System/CodeGeneratorRepository.cs delete mode 100644 ZR.Service/System/CodeGeneratorService.cs diff --git a/ZR.Admin.WebApi/Controllers/CodeGeneratorController.cs b/ZR.Admin.WebApi/Controllers/CodeGeneratorController.cs index 81d751d..92bd1f5 100644 --- a/ZR.Admin.WebApi/Controllers/CodeGeneratorController.cs +++ b/ZR.Admin.WebApi/Controllers/CodeGeneratorController.cs @@ -37,7 +37,6 @@ namespace ZR.Admin.WebApi.Controllers /// [HttpGet("GetListDataBase")] //[YuebonAuthorize("GetListDataBase")] - //[NoPermissionRequired] public IActionResult GetListDataBase() { return SUCCESS(_CodeGeneraterService.GetAllDataBases()); @@ -53,12 +52,8 @@ namespace ZR.Admin.WebApi.Controllers [HttpGet("FindListTable")] public IActionResult FindListTable(string dbName, string tableName, PagerInfo pager) { - if (string.IsNullOrEmpty(dbName)) - { - dbName = "ZrAdmin"; - } - List list = _CodeGeneraterService.GetAllTables(dbName, tableName, pager); - var vm = new VMPageResult(list, pager); + List list = _CodeGeneraterService.GetAllTables(dbName, tableName, pager); + var vm = new VMPageResult(list, pager); return SUCCESS(vm); } @@ -81,7 +76,7 @@ namespace ZR.Admin.WebApi.Controllers } if (string.IsNullOrEmpty(baseSpace)) { - //baseSpace = "Zr"; + baseSpace = "ZR.Admin"; } DbTableInfo dbTableInfo = new() { Name = tables }; CodeGeneratorTool.Generate(dbName, baseSpace, dbTableInfo, replaceTableNameStr, true); diff --git a/ZR.Admin.WebApi/Extensions/EntityExtension.cs b/ZR.Admin.WebApi/Extensions/EntityExtension.cs index d518656..c472ed5 100644 --- a/ZR.Admin.WebApi/Extensions/EntityExtension.cs +++ b/ZR.Admin.WebApi/Extensions/EntityExtension.cs @@ -10,13 +10,13 @@ namespace ZR.Admin.WebApi.Extensions { var types = source.GetType(); - var worker = new IdWorker(1, 1); - if (types.GetProperty("ID") != null) - { - long id = worker.NextId(); + //var worker = new IdWorker(1, 1); + //if (types.GetProperty("ID") != null) + //{ + // long id = worker.NextId(); - types.GetProperty("ID").SetValue(source, id.ToString(), null); - } + // types.GetProperty("ID").SetValue(source, id.ToString(), null); + //} if (types.GetProperty("CreateTime") != null) { diff --git a/ZR.Admin.WebApi/Template/ControllersTemplate.txt b/ZR.Admin.WebApi/Template/ControllersTemplate.txt new file mode 100644 index 0000000..6ff88ef --- /dev/null +++ b/ZR.Admin.WebApi/Template/ControllersTemplate.txt @@ -0,0 +1,124 @@ +using Microsoft.AspNetCore.Mvc; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using ZR.Admin.WebApi.Filters; +using ZR.Admin.WebApi.Controllers; +using ZR.Service; +using SqlSugar; +using Infrastructure; +using Infrastructure.Attribute; +using Infrastructure.Enums; +using Infrastructure.Model; +using Mapster; +using ZR.Admin.WebApi.Extensions; +using ZR.Model; + +namespace ZRAdmin.Controllers +{ + /// + /// T4代码自动生成 + /// + + [Verify] + [Route("bus/<#=ModelName#>")] + public class <#=ControllerName#>Controller: BaseController + { + /// + /// <#=FileName#>接口 + /// + private readonly I<#=ServiceName#> _<#=ServiceName#>; + + public <#=ControllerName#>Controller(I<#=ServiceName#> <#=ServiceName#>) + { + _<#=ServiceName#> = <#=ServiceName#>; + } + + /// + /// 查询<#=FileName#>列表 + /// + /// + [HttpGet("list")] + [ActionPermissionFilter(Permission = "<#=ModelName#>:list")] + public IActionResult Query([FromQuery] <#=ModelName#>QueryDto parm) + { + //开始拼装查询条件 + var predicate = Expressionable.Create<<#=ModelName#>>(); + + //TODO 搜索条件 + //predicate = predicate.And(m => m.Name.Contains(parm.Name)); + + var response = _<#=ServiceName#>.GetPages(predicate.ToExpression(), parm); + + return SUCCESS(response); + } + + /// + /// 查询<#=FileName#>详情 + /// + /// + /// + [HttpGet("{{primaryKey}}")] + public IActionResult Get(int {primaryKey}) + { + var response = _<#=ServiceName#>.GetId({primaryKey}); + + return SUCCESS(response); + } + + /// + /// 添加<#=FileName#> + /// + /// + [HttpPost] + [ActionPermissionFilter(Permission = "<#=ModelName#>:add")] + [Log(Title = "<#=FileName#>添加", BusinessType = BusinessType.INSERT)] + public IActionResult Create([FromBody] <#=ModelName#>Dto parm) + { + if (parm == null) + { + throw new CustomException("请求参数错误"); + } + //从 Dto 映射到 实体 + var addModel = parm.Adapt<<#=ModelName#>>().ToCreate(); + //addModel.CreateID = User.Identity.Name; + + return SUCCESS(_<#=ServiceName#>.Add(addModel)); + } + + /// + /// 更新<#=FileName#> + /// + /// + [HttpPut("edit")] + [ActionPermissionFilter(Permission = "<#=ModelName#>:update")] + [Log(Title = "<#=FileName#>修改", BusinessType = BusinessType.UPDATE)] + public IActionResult Update([FromBody] <#=ModelName#>Dto parm) + { + //从 Dto 映射到 实体 + var addModel = parm.Adapt<<#=ModelName#>>().ToCreate(); + //addModel.CreateID = User.Identity.Name; + //TODO 字段映射 + var response = _<#=ServiceName#>.Update(addModel); + + return SUCCESS(response); + } + + /// + /// 删除<#=FileName#> + /// + /// + [HttpDelete("{{primaryKey}}")] + [ActionPermissionFilter(Permission = "<#=ModelName#>:delete")] + [Log(Title = "<#=FileName#>删除", BusinessType = BusinessType.DELETE)] + public IActionResult Delete(int {primaryKey} = 0) + { + if ({primaryKey} <= 0) { return OutputJson(ApiResult.Error($"删除失败Id 不能为空")); } + + // 删除<#=FileName#> + var response = _<#=ServiceName#>.Delete({primaryKey}); + + return SUCCESS(response); + } + } +} \ No newline at end of file diff --git a/ZR.Admin.WebApi/Template/IServiceTemplate.txt b/ZR.Admin.WebApi/Template/IServiceTemplate.txt new file mode 100644 index 0000000..7bd979a --- /dev/null +++ b/ZR.Admin.WebApi/Template/IServiceTemplate.txt @@ -0,0 +1,13 @@ +using System; +using ZR.Model.System; +using ZR.Model; + +namespace {IServicsNamespace} +{ + /// + /// 定义{TableNameDesc}服务接口 + /// + public interface I{ModelTypeName}Service: IBaseService<{ModelTypeName}> + { + } +} diff --git a/ZR.Admin.WebApi/Template/RepositoryTemplate.txt b/ZR.Admin.WebApi/Template/RepositoryTemplate.txt new file mode 100644 index 0000000..78765e4 --- /dev/null +++ b/ZR.Admin.WebApi/Template/RepositoryTemplate.txt @@ -0,0 +1,24 @@ +using System; +using Infrastructure.Attribute; +using {RepositoriesNamespace}.System; +using {ModelsNamespace}; + +namespace {RepositoriesNamespace} +{ + /// + /// {TableNameDesc}仓储接口的实现 + /// + [AppService(ServiceLifetime = LifeTime.Transient)] + public class {ModelTypeName}Repository : BaseRepository + { + public {ModelTypeName}Repository() + { + } + + #region 业务逻辑代码 + + + + #endregion + } +} \ No newline at end of file diff --git a/ZR.Admin.WebApi/Template/ServiceTemplate.txt b/ZR.Admin.WebApi/Template/ServiceTemplate.txt new file mode 100644 index 0000000..de593c9 --- /dev/null +++ b/ZR.Admin.WebApi/Template/ServiceTemplate.txt @@ -0,0 +1,28 @@ +using Infrastructure; +using Infrastructure.Attribute; +using Infrastructure.Extensions; +using SqlSugar; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using ZR.Common; +using ZR.Model; +using ZR.Repository; +using ZR.Service.IService; + +namespace {ServicesNamespace} +{ + /// + /// {TableNameDesc}服务接口实现 + /// + [AppService(ServiceType = typeof(I{ModelTypeName}Service), ServiceLifetime = LifeTime.Transient)] + public class {ModelTypeName}Service: BaseService<{ModelTypeName}>, I{ModelTypeName}Service + { + private readonly {ModelTypeName}Repository _repository; + public {ModelTypeName}Service({ModelTypeName}Repository repository) + { + _repository = repository; + } + } +} \ No newline at end of file diff --git a/ZR.Admin.WebApi/Template/VueJsTemplate.txt b/ZR.Admin.WebApi/Template/VueJsTemplate.txt new file mode 100644 index 0000000..d882fc9 --- /dev/null +++ b/ZR.Admin.WebApi/Template/VueJsTemplate.txt @@ -0,0 +1,85 @@ +import http from '@/utils/request' +import defaultSettings from '@/settings' + +/** + * {ModelTypeDesc}分页查询 + * @param {查询条件} data + */ +export function get{ModelTypeName}ListWithPager(data) { + return http.request({ + url: '{ModelTypeName}/FindWithPagerAsync', + method: 'post', + data: data, + baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式 + }) +}/** + * 获取所有可用的{ModelTypeDesc} + */ +export function getAll{ModelTypeName}List() { + return http.request({ + url: '{ModelTypeName}/GetAllEnable', + method: 'get', + baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式 + }) +} +/** + * 新增或修改保存{ModelTypeDesc} + * @param data + */ +export function save{ModelTypeName}(data, url) { + return http.request({ + url: url, + method: 'post', + data: data, + baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式 + }) +} +/** + * 获取{ModelTypeDesc}详情 + * @param {Id} {ModelTypeDesc}Id + */ +export function get{ModelTypeName}Detail(id) { + return http({ + url: '{ModelTypeName}/GetById', + method: 'get', + params: { id: id }, + baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式 + }) +} +/** + * 批量设置启用状态 + * @param {id集合} ids + */ +export function set{ModelTypeName}Enable(data) { + return http({ + url: '{ModelTypeName}/SetEnabledMarktBatchAsync', + method: 'post', + data: data, + baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式 + }) +} +/** + * 批量软删除 + * @param {id集合} ids + */ +export function deleteSoft{ModelTypeName}(data) { + return http({ + url: '{ModelTypeName}/DeleteSoftBatchAsync', + method: 'post', + data: data, + baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式 + }) +} + +/** + * 批量删除 + * @param {id集合} ids + */ +export function delete{ModelTypeName}(data) { + return http({ + url: '{ModelTypeName}/DeleteBatchAsync', + method: 'delete', + data: data, + baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式 + }) +} diff --git a/ZR.Admin.WebApi/Template/VueTemplate.txt b/ZR.Admin.WebApi/Template/VueTemplate.txt new file mode 100644 index 0000000..e109a38 --- /dev/null +++ b/ZR.Admin.WebApi/Template/VueTemplate.txt @@ -0,0 +1,249 @@ + + + diff --git a/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj b/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj index 5bbdc8a..cbbf3ed 100644 --- a/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj +++ b/ZR.Admin.WebApi/ZR.Admin.WebApi.csproj @@ -57,12 +57,30 @@ TextTemplatingFileGenerator Controller.cs + + Always + Always + + Always + Always + + Always + + + Always + + + Always + + + Always + @@ -70,6 +88,16 @@ + + + + Always + + + Always + + + diff --git a/ZR.Admin.WebApi/appsettings.Production.json b/ZR.Admin.WebApi/appsettings.Production.json index 4dd2ae0..8dd126d 100644 --- a/ZR.Admin.WebApi/appsettings.Production.json +++ b/ZR.Admin.WebApi/appsettings.Production.json @@ -7,7 +7,8 @@ } }, "ConnectionStrings": { - "Conn_Admin": "server=127.0.0.1;database=admin;user=zr;pwd=abc" + "Conn_Admin": "server=127.0.0.1,1433;database=admin;user=admin;pwd=abc", + "ConnDynamic": "server=127.0.0.1,1433;uid=dev_test;Password=%54Gz@cn;database={database}" }, "urls": "http://localhost:8888", "sysConfig": { diff --git a/ZR.CodeGenerator/CodeGeneratorTool.cs b/ZR.CodeGenerator/CodeGeneratorTool.cs index 5162a9b..2ad6547 100644 --- a/ZR.CodeGenerator/CodeGeneratorTool.cs +++ b/ZR.CodeGenerator/CodeGeneratorTool.cs @@ -43,9 +43,9 @@ namespace ZR.CodeGenerator _option.ModelsNamespace = baseNamespace + "ZR.Model"; //_option.IRepositoriesNamespace = baseNamespace + ".IRepositorie"; _option.RepositoriesNamespace = baseNamespace + "ZR.Repository"; - //_option.IServicsNamespace = baseNamespace + ".IService"; + _option.IServicsNamespace = baseNamespace + "ZR.Service"; _option.ServicesNamespace = baseNamespace + "ZR.Service"; - _option.ApiControllerNamespace = baseNamespace + "Api"; + _option.ApiControllerNamespace = baseNamespace + "ZR.Admin.WebApi"; _option.ReplaceTableNameStr = replaceTableNameStr; //_option.TableList = listTable; @@ -88,6 +88,7 @@ namespace ZR.CodeGenerator var modelsNamespace = _option.ModelsNamespace; var modelTypeName = GetModelName(tableInfo.Name); ;//表名 var modelTypeDesc = tableInfo.Description;//表描述 + var primaryKey = "id";//主键 string keyTypeName = "string";//主键数据类型 string modelcontent = "";//数据库模型字段 @@ -111,6 +112,7 @@ namespace ZR.CodeGenerator modelcontent += " /// \n"; if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey) { + primaryKey = columnName; modelcontent += $" [SqlSugar.SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPrimarykey.ToString().ToLower()}, IsIdentity = {dbFieldInfo.IsIdentity.ToString().ToLower()})]\n"; } modelcontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r"; @@ -121,39 +123,43 @@ namespace ZR.CodeGenerator //} //outputDtocontent += string.Format(" public {0} {1}", dbFieldInfo.DataType, columnName); //outputDtocontent += " { get; set; }\n\r"; - //if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint") - //{ + if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint") + { - // vueViewListContent += string.Format(" \n", columnName, dbFieldInfo.ColumnDescription); - // vueViewListContent += " \n"; - // vueViewListContent += " \n"; + vueViewListContent += string.Format(" \n", columnName, dbFieldInfo.ColumnDescription); + vueViewListContent += " \n"; + vueViewListContent += " \n"; - // vueViewFromContent += string.Format(" ", dbFieldInfo.ColumnDescription, columnName); - // vueViewFromContent += string.Format(" \n", columnName); - // vueViewFromContent += " \n"; - // vueViewFromContent += " \n"; - // vueViewFromContent += " \n"; - // vueViewFromContent += " \n"; + vueViewFromContent += string.Format(" ", dbFieldInfo.ColumnDescription, columnName); + vueViewFromContent += string.Format(" \n", columnName); + vueViewFromContent += " \n"; + vueViewFromContent += " \n"; + vueViewFromContent += " \n"; + vueViewFromContent += " \n"; - // vueViewEditFromContent += string.Format(" {0}: 'true',\n", columnName); - // vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.ResData.{0}+''\n", columnName); - //} - //else - //{ - // vueViewListContent += string.Format(" \n", columnName, dbFieldInfo.ColumnDescription); + vueViewEditFromContent += string.Format(" {0}: 'true',\n", columnName); + vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.data.{0}+''\n", columnName); + } + else + { + //table-column + vueViewListContent += $" \n"; - // vueViewFromContent += string.Format(" \n", dbFieldInfo.ColumnDescription, columnName); - // vueViewFromContent += string.Format(" \n", columnName, dbFieldInfo.ColumnDescription); - // vueViewFromContent += " \n"; - // vueViewEditFromContent += string.Format(" {0}: '',\n", columnName); - // vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.ResData.{0}\n", columnName); - //} + //form-item + vueViewFromContent += $" \n"; + vueViewFromContent += $" \n"; + vueViewFromContent += " \n"; + vueViewEditFromContent += string.Format(" {0}: '',\n", columnName); + vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.ResData.{0}\n", columnName); + } //vueViewSaveBindContent += string.Format(" '{0}':this.editFrom.{0},\n", columnName); + + //Rule 规则验证 //if (!dbFieldInfo.IsNullable) //{ // vueViewEditFromRuleContent += string.Format(" {0}: [\n", columnName); @@ -169,23 +175,20 @@ namespace ZR.CodeGenerator InputDtocontent += " /// \n"; InputDtocontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription); InputDtocontent += " /// \n"; - //if (dbFieldInfo.FieldType == "string") - //{ - // InputDtocontent += string.Format(" [MaxLength({0})]\n", dbFieldInfo.FieldMaxLength); - //} InputDtocontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r"; //} // } - GenerateModels(modelsNamespace, modelTypeName, tableInfo.Name, modelcontent, modelTypeDesc, keyTypeName, ifExsitedCovered); - GenerateInputDto(modelsNamespace, modelTypeName, modelTypeDesc, InputDtocontent, keyTypeName, ifExsitedCovered); - //GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); - //GenerateRepository(modelTypeName, modelTypeDesc, tableInfo.TableName, keyTypeName, ifExsitedCovered); + //GenerateModels(modelsNamespace, modelTypeName, tableInfo.Name, modelcontent, modelTypeDesc, keyTypeName, ifExsitedCovered); + //GenerateInputDto(modelsNamespace, modelTypeName, modelTypeDesc, InputDtocontent, keyTypeName, ifExsitedCovered); + //GenerateRepository(modelTypeName, modelTypeDesc, tableInfo.Name, keyTypeName, ifExsitedCovered); //GenerateIService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); //GenerateService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); + //GenerateControllers(modelTypeName, primaryKey, modelTypeDesc, keyTypeName, ifExsitedCovered); + + //GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); //GenerateOutputDto(modelTypeName, modelTypeDesc, outputDtocontent, ifExsitedCovered); - //GenerateControllers(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); - //GenerateVueViews(modelTypeName, modelTypeDesc, vueViewListContent, vueViewFromContent, vueViewEditFromContent, vueViewEditFromBindContent, vueViewSaveBindContent, vueViewEditFromRuleContent, ifExsitedCovered); + GenerateVueViews(modelTypeName, primaryKey, modelTypeDesc, vueViewListContent, vueViewFromContent, vueViewEditFromContent, vueViewEditFromBindContent, vueViewSaveBindContent, vueViewEditFromRuleContent, ifExsitedCovered); } @@ -261,6 +264,210 @@ namespace ZR.CodeGenerator } #endregion + #region 生成Repository + + /// + /// 生成Repository层代码文件 + /// + /// + /// + /// 表名 + /// + /// 如果目标文件存在,是否覆盖。默认为false + private static void GenerateRepository(string modelTypeName, string modelTypeDesc, string tableName, string keyTypeName, bool ifExsitedCovered = false) + { + //var path = AppDomain.CurrentDomain.BaseDirectory; + var parentPath = "..";// path.Substring(0, path.LastIndexOf("\\")); + var repositoryPath = parentPath + "\\" + _option.BaseNamespace + "\\" + _option.RepositoriesNamespace; + if (!Directory.Exists(repositoryPath)) + { + //repositoryPath = parentPath + "\\" + _option.BaseNamespace + "\\Repositories"; + Directory.CreateDirectory(repositoryPath); + } + var fullPath = repositoryPath + "\\" + modelTypeName + "Repository.cs"; + if (File.Exists(fullPath) && !ifExsitedCovered) + return; + var content = ReadTemplate("RepositoryTemplate.txt"); + content = content.Replace("{ModelsNamespace}", _option.ModelsNamespace) + .Replace("{IRepositoriesNamespace}", _option.IRepositoriesNamespace) + .Replace("{RepositoriesNamespace}", _option.RepositoriesNamespace) + .Replace("{ModelTypeName}", modelTypeName) + .Replace("{TableNameDesc}", modelTypeDesc) + .Replace("{TableName}", tableName) + .Replace("{KeyTypeName}", keyTypeName); + WriteAndSave(fullPath, content); + } + + #endregion + + #region 生成Service + /// + /// 生成IService文件 + /// + /// + /// + /// + /// + /// 如果目标文件存在,是否覆盖。默认为false + private static void GenerateIService(string modelsNamespace, string modelTypeName, string modelTypeDesc, string keyTypeName, bool ifExsitedCovered = false) + { + //var path = AppDomain.CurrentDomain.BaseDirectory; + //path = path.Substring(0, path.IndexOf("\\bin")); + var parentPath = "..";// path.Substring(0, path.LastIndexOf("\\")); + var iServicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + _option.IServicsNamespace; + if (!Directory.Exists(iServicesPath)) + { + iServicesPath = parentPath + "\\" + _option.BaseNamespace + "\\IBusService"; + Directory.CreateDirectory(iServicesPath); + } + var fullPath = $"{iServicesPath}\\Business\\IService\\I{modelTypeName}Service.cs"; + if (File.Exists(fullPath) && !ifExsitedCovered) + return; + var content = ReadTemplate("IServiceTemplate.txt"); + content = content.Replace("{ModelsNamespace}", modelsNamespace) + .Replace("{DtosNamespace}", _option.DtosNamespace) + .Replace("{TableNameDesc}", modelTypeDesc) + .Replace("{IServicsNamespace}", _option.IServicsNamespace) + .Replace("{ModelTypeName}", modelTypeName) + .Replace("{KeyTypeName}", keyTypeName); + WriteAndSave(fullPath, content); + } + + /// + /// 生成Service文件 + /// + /// + /// + /// + /// + /// 如果目标文件存在,是否覆盖。默认为false + private static void GenerateService(string modelsNamespace, string modelTypeName, string modelTypeDesc, string keyTypeName, bool ifExsitedCovered = false) + { + //var path = AppDomain.CurrentDomain.BaseDirectory; + //path = path.Substring(0, path.IndexOf("\\bin")); + var parentPath = "..";// path.Substring(0, path.LastIndexOf("\\")); + var servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + _option.ServicesNamespace; + if (!Directory.Exists(servicesPath)) + { + servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\Business"; + Directory.CreateDirectory(servicesPath); + } + var fullPath = servicesPath + "\\Business\\" + modelTypeName + "Service.cs"; + Console.WriteLine(fullPath); + if (File.Exists(fullPath) && !ifExsitedCovered) + return; + var content = ReadTemplate("ServiceTemplate.txt"); + content = content + .Replace("{IRepositoriesNamespace}", _option.IRepositoriesNamespace) + .Replace("{DtosNamespace}", _option.DtosNamespace) + .Replace("{IServicsNamespace}", _option.IServicsNamespace) + .Replace("{TableNameDesc}", modelTypeDesc) + .Replace("{ModelsNamespace}", modelsNamespace) + .Replace("{ServicesNamespace}", _option.ServicesNamespace) + .Replace("{ModelTypeName}", modelTypeName) + .Replace("{KeyTypeName}", keyTypeName); + WriteAndSave(fullPath, content); + } + + #endregion + + #region 生成Controller + /// + /// 生成控制器ApiControllers文件 + /// + /// 实体类型名称 + /// 主键 + /// 实体描述 + /// + /// 如果目标文件存在,是否覆盖。默认为false + private static void GenerateControllers(string modelTypeName, string primaryKey, string modelTypeDesc, string keyTypeName, bool ifExsitedCovered = false) + { + //var servicesNamespace = _option.DtosNamespace; + //var fileClassName = _option.BaseNamespace.Substring(_option.BaseNamespace.IndexOf('.') + 1); + //var path = AppDomain.CurrentDomain.BaseDirectory; + //path = path.Substring(0, path.IndexOf("\\bin")); + var parentPath = "..";//path.Substring(0, path.LastIndexOf("\\")); + var servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + _option.ApiControllerNamespace; + if (!Directory.Exists(servicesPath)) + { + servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\Controllers\\"; + Directory.CreateDirectory(servicesPath); + } + var fullPath = servicesPath + "\\Controllers\\business\\" + modelTypeName + "Controller.cs"; + Console.WriteLine(fullPath); + if (File.Exists(fullPath) && !ifExsitedCovered) + return; + var content = ReadTemplate("ControllersTemplate.txt"); + content = content + //.Replace("{DtosNamespace}", _option.DtosNamespace) + .Replace("<#=ControllerName#>", modelTypeName) + //.Replace("{ModelsNamespace}", _option.ModelsNamespace) + .Replace("<#=FileName#>", modelTypeDesc) + .Replace("<#=ServiceName#>", modelTypeName + "Service") + .Replace("<#=ModelName#>", modelTypeName) + .Replace("{primaryKey}", primaryKey) + .Replace("{KeyTypeName}", keyTypeName); + WriteAndSave(fullPath, content); + } + #endregion + + #region 生成Vue页面 + /// + /// 生成Vue页面 + /// + /// 类名 + /// 表/类描述 + /// + /// + /// + /// + /// + /// + /// 如果目标文件存在,是否覆盖。默认为false + private static void GenerateVueViews(string modelTypeName, string primaryKey, string modelTypeDesc, string vueViewListContent, string vueViewFromContent, string vueViewEditFromContent, string vueViewEditFromBindContent, string vueViewSaveBindContent, string vueViewEditFromRuleContent, bool ifExsitedCovered = false) + { + var servicesNamespace = _option.DtosNamespace; + var fileClassName = _option.BaseNamespace.Substring(_option.BaseNamespace.IndexOf('.') + 1); + var path = AppDomain.CurrentDomain.BaseDirectory; + //path = path.Substring(0, path.IndexOf("\\bin")); + var parentPath = path.Substring(0, path.LastIndexOf("\\")); + var servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + servicesNamespace; + if (!Directory.Exists(servicesPath)) + { + servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\vue\\" + modelTypeName.ToLower(); + Directory.CreateDirectory(servicesPath); + } + var fullPath = servicesPath + "\\" + "index.vue"; + if (File.Exists(fullPath) && !ifExsitedCovered) + return; + var content = ReadTemplate("VueTemplate.txt"); + content = content + .Replace("{BaseNamespace}", fileClassName.ToLower()) + .Replace("{fileClassName}", modelTypeName.ToLower()) + .Replace("{ModelTypeNameToLower}", modelTypeName.ToLower()) + .Replace("{VueViewListContent}", vueViewListContent) + .Replace("{VueViewFromContent}", vueViewFromContent) + .Replace("{ModelTypeName}", modelTypeName) + .Replace("{VueViewEditFromContent}", vueViewEditFromContent) + .Replace("{VueViewEditFromBindContent}", vueViewEditFromBindContent) + .Replace("{VueViewSaveBindContent}", vueViewSaveBindContent) + .Replace("{primaryKey}", primaryKey) + .Replace("{VueViewEditFromRuleContent}", vueViewEditFromRuleContent); + WriteAndSave(fullPath, content); + + fullPath = servicesPath + "\\" + modelTypeName.ToLower() + ".js"; + if (File.Exists(fullPath) && !ifExsitedCovered) + return; + content = ReadTemplate("VueJsTemplate.txt"); + content = content + .Replace("{ModelTypeName}", modelTypeName) + .Replace("{ModelTypeDesc}", modelTypeDesc) + .Replace("{fileClassName}", fileClassName); + WriteAndSave(fullPath, content); + } + + #endregion + #region 帮助方法 private static string GetModelName(string modelTypeName) @@ -273,7 +480,19 @@ namespace ZR.CodeGenerator modelTypeName = modelTypeName.Substring(0, 1).ToUpper() + modelTypeName.Substring(1); return modelTypeName; } - + private static string FirstLowerCase(string str) + { + if (string.IsNullOrEmpty(str)) + { + return str; + } + str = str.Substring(0, 1).ToLower() + str.Substring(1); + return str; + } + private static string GetLabelName(string columnDescription, string columnName) + { + return string.IsNullOrEmpty(columnDescription) ? columnName : columnDescription; + } /// /// 从代码模板中读取内容 /// @@ -309,17 +528,24 @@ namespace ZR.CodeGenerator /// private static void WriteAndSave(string fileName, string content) { - //实例化一个文件流--->与写入文件相关联 - using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); - //实例化一个StreamWriter-->与fs相关联 - using var sw = new StreamWriter(fs); - //开始写入 - sw.Write(content); - //清空缓冲区 - sw.Flush(); - //关闭流 - sw.Close(); - fs.Close(); + try + { + //实例化一个文件流--->与写入文件相关联 + using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); + //实例化一个StreamWriter-->与fs相关联 + using var sw = new StreamWriter(fs); + //开始写入 + sw.Write(content); + //清空缓冲区 + sw.Flush(); + //关闭流 + sw.Close(); + fs.Close(); + } + catch (Exception ex) + { + Console.WriteLine("写入文件出错了:" + ex.Message); + } } #endregion diff --git a/ZR.CodeGenerator/DbProvider.cs b/ZR.CodeGenerator/DbProvider.cs index ed3757e..56525f3 100644 --- a/ZR.CodeGenerator/DbProvider.cs +++ b/ZR.CodeGenerator/DbProvider.cs @@ -10,13 +10,23 @@ namespace ZR.CodeGenerator { public class DbProvider { + protected static SqlSugarScope CodeDb; - public SqlSugarClient GetSugarDbContext(string dbName) + /// + /// 获取动态连接字符串 + /// + /// 数据库名 + /// + public SqlSugarScope GetSugarDbContext(string dbName = "") { - string connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.Conn).Replace("{DbName}", dbName); + string connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.Conn).Replace("{database}", dbName); int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.CodeGenDbType, 0); - - return new SqlSugarClient(new List() + if (string.IsNullOrEmpty(dbName)) + { + connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.ConnAdmin); + dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.DbType, 0); + } + var db = new SqlSugarScope(new List() { new ConnectionConfig(){ ConnectionString = connStr, @@ -25,6 +35,9 @@ namespace ZR.CodeGenerator InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息 }, }); + + CodeDb = db; + return db; } } } diff --git a/ZR.CodeGenerator/Service/CodeGeneraterService.cs b/ZR.CodeGenerator/Service/CodeGeneraterService.cs index a66aa0c..f24f4e1 100644 --- a/ZR.CodeGenerator/Service/CodeGeneraterService.cs +++ b/ZR.CodeGenerator/Service/CodeGeneraterService.cs @@ -1,16 +1,12 @@ -using Infrastructure; -using SqlSugar; -using System; +using SqlSugar; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using ZR.Model; using ZR.Model.CodeGenerator; namespace ZR.CodeGenerator.Service { - public class CodeGeneraterService: DbProvider + public class CodeGeneraterService : DbProvider { /// /// 获取所有数据库名 @@ -18,21 +14,15 @@ namespace ZR.CodeGenerator.Service /// public List GetAllDataBases() { - var dbType = ConfigUtils.Instance.GetConfig("CodeGenDbType"); - List list = new List(); - if (dbType == "1") + List list = new(); + + var db = GetSugarDbContext(); + var templist = db.DbMaintenance.GetDataBaseList(db.ScopedContext); + templist.ForEach(item => { - var db = GetSugarDbContext("ZrAdmin"); - var templist = db.DbMaintenance.GetDataBaseList(db); - templist.ForEach(item => - { - list.Add(new DataBaseInfo() { DbName = item }); - }); - } - else if (dbType == "0") - { - // list = mssqlExtractor.GetAllDataBases(); - } + list.Add(new DataBaseInfo() { DbName = item }); + }); + return list; } @@ -43,7 +33,7 @@ namespace ZR.CodeGenerator.Service /// /// /// - public List GetAllTables(string dbName, string tableName, PagerInfo pager) + public List GetAllTables(string dbName, string tableName, PagerInfo pager) { var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true); if (!string.IsNullOrEmpty(tableName)) @@ -62,7 +52,7 @@ namespace ZR.CodeGenerator.Service /// public List GetColumnInfo(string dbName, string tableName) { - return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true); + return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true); } } diff --git a/ZR.Repository/System/CodeGeneratorRepository.cs b/ZR.Repository/System/CodeGeneratorRepository.cs deleted file mode 100644 index 7c1888e..0000000 --- a/ZR.Repository/System/CodeGeneratorRepository.cs +++ /dev/null @@ -1,75 +0,0 @@ -using Infrastructure.Attribute; -using SqlSugar; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ZR.Model; -using ZR.Model.CodeGenerator; - -namespace ZR.Repository.System -{ - [AppService(ServiceLifetime = LifeTime.Transient)] - public class CodeGeneratorRepository : BaseRepository - { - ///// - ///// 获取数据库 - ///// - ///// - //public List GetAllDb() - //{ - // //return Db.Ado.SqlQuery("select name as DbName from master..sysdatabases "); - // var list = Db.DbMaintenance.GetDataBaseList(Db); - // List dataBases = new List(); - // list.ForEach(item => - // { - // dataBases.Add(new DataBaseInfo() { DbName = item }); - // }); - // return dataBases; - //} - - ///// - ///// 根据数据库名获取所有的表 - ///// - ///// - ///// - ///// - ///// - //public List GetAllTables(string dbName, string tableName, PagerInfo pager) - //{ - // var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true); - // if (!string.IsNullOrEmpty(tableName)) - // { - // tableList = tableList.Where(f => f.Name.Contains(tableName)).ToList(); - // } - // pager.TotalNum = tableList.Count; - // return tableList.Skip(pager.PageSize * (pager.PageNum - 1)).Take(pager.PageSize).OrderBy(f => f.Name).ToList(); - //} - - ///// - ///// 获取表格列信息 - ///// - ///// - ///// - ///// - //public List GetColumnInfo(string dbName, string tableName) - //{ - // return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true); - //} - - - /// - /// 获取当前数据库表名 - /// - /// - /// - //public List GetAllTables(string[] tabList) - //{ - // string sql = @"SELECT tbs.name as TableName ,ds.value as Description FROM sys.tables tbs - // left join sys.extended_properties ds on ds.major_id=tbs.object_id and ds.minor_id=0"; - - // return Db.SqlQueryable(sql).WhereIF(tabList.Length > 0, x => tabList.Contains(x.TableName)).ToList(); - //} - } -} diff --git a/ZR.Service/System/CodeGeneratorService.cs b/ZR.Service/System/CodeGeneratorService.cs deleted file mode 100644 index 7c8446e..0000000 --- a/ZR.Service/System/CodeGeneratorService.cs +++ /dev/null @@ -1,99 +0,0 @@ -using Infrastructure; -using Infrastructure.Attribute; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using ZR.Model; -using ZR.Model.CodeGenerator; -using ZR.Repository.System; -using ZR.Service.IService; - -namespace ZR.Service.System -{ - /// - /// - /// - //[AppService(ServiceType = typeof(ICodeGeneratorService), ServiceLifetime = LifeTime.Transient)] - public class CodeGeneratorService //: ICodeGeneratorService - { - //public CodeGeneratorRepository CodeGeneratorRepository; - - //public CodeGeneratorService(CodeGeneratorRepository codeGeneratorRepository) - //{ - // CodeGeneratorRepository = codeGeneratorRepository; - //} - - ///// - ///// 获取表所有列 - ///// - ///// - ///// - //public List GetAllColumns(string tableName) - //{ - // var dbType = ConfigUtils.Instance.GetConfig("CodeGenDbType"); - // if (tableName == null) - // throw new ArgumentException(nameof(tableName)); - // List list = new List(); - // if (dbType == "1") - // { - // list = CodeGeneratorRepository.GetAllColumns(tableName); - // } - // return list; - //} - - ///// - ///// 获取所有数据库名 - ///// - ///// - //public List GetAllDataBases() - //{ - // var dbType = ConfigUtils.Instance.GetConfig("CodeGenDbType"); - // List list = new List(); - // if (dbType == "1") - // { - // list = CodeGeneratorRepository.GetAllDb(); - // } - // else if (dbType == "0") - // { - // // list = mssqlExtractor.GetAllDataBases(); - // } - // return list; - //} - - //public List GetAllTables(string tableStrs) - //{ - // string[] tabList = tableStrs.Split(","); - - // return CodeGeneratorRepository.GetAllTables(tabList); - //} - - /// - /// 获取列信息 - /// - /// - /// - /// - //public List GetColumnInfo(string dbName, string tableName) - //{ - // return CodeGeneratorRepository.GetColumnInfo(dbName, tableName); - //} - - //public List GetTablesWithPage(string tablename, string dbName, PagerInfo pager) - //{ - // var dbType = ConfigUtils.Instance.GetConfig("CodeGenDbType"); - // List list = new List(); - // if (dbType == "1") - // { - // list = CodeGeneratorRepository.GetAllTables(dbName, tablename, pager); - // } - // else if (dbType == "0") - // { - // //list = mysqlExtractor.GetAllTables(this.dbName, tablename, fieldNameToSort, isDescending, info); - // } - // return list; - //} - - } -} diff --git a/ZR.Service/ZR.Service.csproj b/ZR.Service/ZR.Service.csproj index 6f3c4d0..7d41173 100644 --- a/ZR.Service/ZR.Service.csproj +++ b/ZR.Service/ZR.Service.csproj @@ -9,4 +9,8 @@ + + + + diff --git a/ZR.Vue/src/views/tool/index.vue b/ZR.Vue/src/views/tool/index.vue index b291e7c..dcdeef6 100644 --- a/ZR.Vue/src/views/tool/index.vue +++ b/ZR.Vue/src/views/tool/index.vue @@ -32,30 +32,26 @@
- - - - - - + + + + - - 查询 - - + + 查询 刷新 @@ -105,7 +101,7 @@ export default { DbType: "", }, searchform: { - DbName: "", + dbName: "", tableName: "", }, codeform: { @@ -122,6 +118,9 @@ export default { // trigger: "blur", // }, // ], + dbName: [ + { required: true, message: "请选择数据库名称", trigger: "blur" }, + ], replaceTableNameStr: [ { min: 0, max: 50, message: "长度小于50个字符", trigger: "blur" }, ], @@ -166,15 +165,13 @@ export default { * 加载页面table数据 */ loadTableData: function () { - if (this.searchform.dataBaseName !== "") { + if (this.codeform.dataBaseName !== "") { this.tableloading = true; var seachdata = { pageNum: this.pagination.pageNum, PageSize: this.pagination.pagesize, - tableName: this.searchform.tableName, - dbName: this.searchform.DbName, - // Order: this.sortableData.order, - // Sort: this.sortableData.sort, + tableName: this.codeform.tableName, + dbName: this.codeform.dbName, }; codeGetTableList(seachdata).then((res) => { this.tableData = res.data.result; @@ -187,9 +184,15 @@ export default { * 点击查询 */ handleSearch: function () { - this.tableloading = true; - this.pagination.pageNum = 1; - this.loadTableData(); + this.$refs["codeform"].validate((valid) => { + if (valid) { + this.tableloading = true; + this.pagination.pageNum = 1; + this.loadTableData(); + }else{ + return false; + } + }); }, handleShowTable: function () { this.pagination.pageNum = 1; @@ -231,7 +234,7 @@ export default { const pageLoading = Loading.service(loadop); var seachdata = { - dbName: this.searchform.DbName, + dbName: this.codeform.dbName, tables: row.name, // this.currentSelected.toString(), baseSpace: this.codeform.baseSpace, replaceTableNameStr: this.codeform.replaceTableNameStr,