using Newtonsoft.Json.Linq; using SqlSugar; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; using HT.Cloud.Code; using HT.Cloud.Domain.SystemManage; namespace HT.Cloud.CodeGenerator { public class SingleTableTemplate { private string authorizecacheKey = GlobalContext.SystemConfig.ProjectPrefix + "_authorizeurldata_";// +权限 private ISqlSugarClient _context; public SingleTableTemplate(ISqlSugarClient context) { _context = context; } #region GetBaseConfig public BaseConfigModel GetBaseConfig(string path, string username, string tableName, string tableDescription, List tableFieldList) { path = GetProjectRootPath(path); BaseConfigModel baseConfigModel = new BaseConfigModel(); baseConfigModel.TableName = tableName; baseConfigModel.TableNameUpper = TableMappingHelper.ConvertTo_Uppercase(tableName); #region FileConfigModel baseConfigModel.FileConfig = new FileConfigModel(); baseConfigModel.FileConfig.ClassPrefix = TableMappingHelper.GetClassNamePrefix(tableName); baseConfigModel.FileConfig.ClassDescription = tableDescription; baseConfigModel.FileConfig.CreateUserName = username; baseConfigModel.FileConfig.CreateDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm"); baseConfigModel.FileConfig.EntityName = string.Format("{0}Entity", baseConfigModel.FileConfig.ClassPrefix); baseConfigModel.FileConfig.ServiceName = string.Format("{0}Service", baseConfigModel.FileConfig.ClassPrefix); baseConfigModel.FileConfig.ControllerName = string.Format("{0}Controller", baseConfigModel.FileConfig.ClassPrefix); baseConfigModel.FileConfig.PageIndexName = "Index"; baseConfigModel.FileConfig.PageFormName = "Form"; baseConfigModel.FileConfig.PageDetailsName = "Details"; #endregion FileConfigModel #region OutputConfigModel baseConfigModel.OutputConfig = new OutputConfigModel(); baseConfigModel.OutputConfig.OutputModule = string.Empty; baseConfigModel.OutputConfig.OutputEntity = Path.Combine(path, "HT.Cloud.Domain\\Entity"); baseConfigModel.OutputConfig.OutputService = Path.Combine(path, "HT.Cloud.Service"); baseConfigModel.OutputConfig.OutputWeb = Path.Combine(path, "HT.Cloud.Web"); #endregion OutputConfigModel #region PageIndexModel baseConfigModel.PageIndex = new PageIndexModel(); baseConfigModel.PageIndex.IsMunu = true; baseConfigModel.PageIndex.IsTree = false; baseConfigModel.PageIndex.IsSearch = true; baseConfigModel.PageIndex.IsFields = false; baseConfigModel.PageIndex.IsPagination = true; baseConfigModel.PageIndex.IsFields = false; baseConfigModel.PageIndex.IsPublic = false; baseConfigModel.PageIndex.IsCache = false; baseConfigModel.PageIndex.IsAsc = false; baseConfigModel.PageIndex.SortColumn = "F_Id"; baseConfigModel.PageIndex.ButtonList = new List(); baseConfigModel.PageIndex.ColumnList = tableFieldList; baseConfigModel.PageIndex.KeywordColum = new List(); baseConfigModel.PageIndex.KeywordColum.Add("F_EnCode"); baseConfigModel.PageIndex.KeywordColum.Add("F_FullName"); baseConfigModel.PageIndex.ParentColum = "F_ParentId"; baseConfigModel.PageIndex.TreeColum = "F_FullName"; baseConfigModel.PageIndex.DeleteColum = "F_DeleteMark"; baseConfigModel.PageIndex.CreateColum = "F_CreatorTime"; #endregion PageIndexModel #region PageFormModel baseConfigModel.PageForm = new PageFormModel(); baseConfigModel.PageForm.ShowMode = 1; baseConfigModel.PageForm.FieldList = new Dictionary(); #endregion PageFormModel return baseConfigModel; } #endregion GetBaseConfig #region BuildEntity public string BuildEntity(BaseConfigModel baseConfigModel, DataTable dt, string idColumn = "F_Id", bool keyIsNull = false) { StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); //sb.AppendLine("using Newtonsoft.Json;"); //sb.AppendLine("using HT.Cloud.Code;"); sb.AppendLine("using System.ComponentModel.DataAnnotations;"); sb.AppendLine("using SqlSugar;"); sb.AppendLine(); sb.AppendLine("namespace HT.Cloud.Domain." + baseConfigModel.OutputConfig.OutputModule); sb.AppendLine("{"); SetClassDescription("实体类", baseConfigModel, sb); baseConfigModel.TableNameUpper = TableMappingHelper.ConvertTo_Uppercase(baseConfigModel.TableName); sb.AppendLine(" [SugarTable(\"" + baseConfigModel.TableName + "\")]"); var baseEntity = GetBaseEntity(baseConfigModel.FileConfig.EntityName, dt, idColumn, keyIsNull); if (string.IsNullOrEmpty(baseEntity)) { sb.AppendLine(" public class " + baseConfigModel.FileConfig.EntityName); } else { sb.AppendLine(" public class " + baseConfigModel.FileConfig.EntityName + " : " + baseEntity); } sb.AppendLine(" {"); var list = dt.ToDataList(); foreach (var item in list) { var datatype = TableMappingHelper.GetPropertyDatatype(item.DataType); var isPrimaryKey = idColumn == item.DbColumnName ? ",IsPrimaryKey = true" : ""; var isIdentity = item.IsIdentity ? ",IsIdentity = true" : ""; var isNull = (item.IsNullable && datatype != "string") ? "?" : ""; var isIgnore = item.TableName.IsNullOrZero() ? ",IsIgnore = true" : ""; var isJson = item.DataType.ToLower().StartsWith("json") ? ",IsJson= true" : ""; var columntype = item.DataType; if (item.Length != 0) { columntype = columntype + "(" + item.Length + ")"; } var IsNullable = ""; if (item.IsNullable) { IsNullable = ", IsNullable = true"; } if (isIgnore != "") { isPrimaryKey = isIdentity = isNull = ""; } sb.AppendLine(" /// "); sb.AppendLine(" /// " + item.ColumnDescription); sb.AppendLine(" /// "); sb.AppendLine(" [SugarColumn(ColumnName=\"" + item.DbColumnName + "\", ColumnDescription = \"" + item.ColumnDescription + "\",ColumnDataType = \"" + columntype + "\"" + IsNullable + isIgnore + isJson + isIdentity + isPrimaryKey + ")]"); sb.AppendLine(" public " + datatype + isNull + " " + item.DbColumnName + " { get; set; }"); //switch (datatype) //{ // case "long?": // sb.AppendLine(" [JsonConverter(typeof(StringJsonConverter))]"); // break; // case "DateTime?": // sb.AppendLine(" [JsonConverter(typeof(DateTimeJsonConverter))]"); // break; //} } sb.AppendLine(" }"); sb.AppendLine("}"); return sb.ToString(); } #endregion BuildEntity #region BuildService public string BuildService(BaseConfigModel baseConfigModel, DataTable dt, string idColumn = "F_Id", string idType = "int") { var baseEntity = GetBaseEntity(baseConfigModel.FileConfig.EntityName, dt, idColumn); StringBuilder sb = new StringBuilder(); string method = string.Empty; sb.AppendLine("using System;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Threading.Tasks;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using HT.Cloud.Code;"); sb.AppendLine("using SqlSugar;"); sb.AppendLine("using HT.Cloud.DataBase;"); sb.AppendLine("using HT.Cloud.Domain." + baseConfigModel.OutputConfig.OutputModule + ";"); sb.AppendLine(); sb.AppendLine("namespace HT.Cloud.Service." + baseConfigModel.OutputConfig.OutputModule); sb.AppendLine("{"); SetClassDescription("服务类", baseConfigModel, sb); sb.AppendLine(" public class " + baseConfigModel.FileConfig.ServiceName + " : BaseService<" + baseConfigModel.FileConfig.EntityName + ">, IDenpendency"); sb.AppendLine(" {"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" private string cacheKey = GlobalContext.SystemConfig.ProjectPrefix + \"_" + baseConfigModel.FileConfig.ClassPrefix.ToLower() + "data_\";"); } sb.AppendLine(" public " + baseConfigModel.FileConfig.ServiceName + "(ISqlSugarClient context) : base(context)"); sb.AppendLine(" {"); sb.AppendLine(" }"); sb.AppendLine(" #region 获取数据"); sb.AppendLine(" public async Task> GetList(string keyword = \"\")"); sb.AppendLine(" {"); if (baseConfigModel.PageIndex.IsCache == false) { sb.AppendLine(" var data = repository.IQueryable();"); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); for (int i = 0; i < baseConfigModel.PageIndex.KeywordColum.Count; i++) { if (i == 0) { sb.AppendLine($" data = data.Where(a => a.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } else { sb.AppendLine($" || a.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } } sb.AppendLine(" }"); sb.AppendLine(" return await data" + (string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum) ? "" : $".Where(a => a.{baseConfigModel.PageIndex.DeleteColum} == false)") + $".OrderBy(a => a.{baseConfigModel.PageIndex.SortColumn}" + (baseConfigModel.PageIndex.IsAsc == true ? "" : " , OrderByType.Desc") + ").ToListAsync();"); } else { sb.AppendLine(" var data = await repository.CheckCacheList(cacheKey + \"list\");"); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); for (int i = 0; i < baseConfigModel.PageIndex.KeywordColum.Count; i++) { if (i == 0) { sb.AppendLine($" data = data.Where(t => a.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ").ToList();" : "")); } else { sb.AppendLine($" || a.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ").ToList();" : "")); } } sb.AppendLine(" }"); sb.AppendLine(" return data." + (string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum) ? "" : $"Where(a => a.{baseConfigModel.PageIndex.DeleteColum} == false).") + (baseConfigModel.PageIndex.IsAsc == true ? "OrderBy" : "OrderByDesc") + $"(a => a.{baseConfigModel.PageIndex.SortColumn}).ToList();"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" public async Task> GetLookList(string keyword = \"\")"); sb.AppendLine(" {"); sb.AppendLine($" var query = repository.IQueryable()" + (string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum) ? ";" : $".Where(a => a.{baseConfigModel.PageIndex.DeleteColum} == false);")); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); sb.AppendLine(" //此处需修改"); for (int i = 0; i < baseConfigModel.PageIndex.KeywordColum.Count; i++) { if (i == 0) { sb.AppendLine($" query = query.Where(a => a.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } else { sb.AppendLine($" || a.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } } sb.AppendLine(" }"); sb.AppendLine(" //权限过滤"); sb.AppendLine(" query = GetDataPrivilege(\"a\", \"\", query);"); sb.AppendLine(" return await query.OrderBy(" + $"a => a.{baseConfigModel.PageIndex.SortColumn}" + (baseConfigModel.PageIndex.IsAsc == true ? "" : " , OrderByType.Desc") + ").ToListAsync();"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" public async Task> GetLookList(SoulPage<" + baseConfigModel.FileConfig.EntityName + "> pagination,string keyword = \"\"," + idType + " id=\"\")"); sb.AppendLine(" {"); sb.AppendLine($" var query = repository.IQueryable()" + (string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum) ? ";" : $".Where(a => a.{baseConfigModel.PageIndex.DeleteColum} == false);")); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); for (int i = 0; i < baseConfigModel.PageIndex.KeywordColum.Count; i++) { if (i == 0) { sb.AppendLine($" query = query.Where(a => a.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } else { sb.AppendLine($" || a.{baseConfigModel.PageIndex.KeywordColum[i]}.Contains(keyword)" + (i == baseConfigModel.PageIndex.KeywordColum.Count - 1 ? ");" : "")); } } sb.AppendLine(" }"); if (idType == "int" || idType == "long") { sb.AppendLine(" if(id == 0)"); } else { sb.AppendLine(" if(!string.IsNullOrEmpty(id))"); } sb.AppendLine(" {"); sb.AppendLine(" query= query.Where(a=>a." + idColumn + "==id);"); sb.AppendLine(" }"); sb.AppendLine(" //权限过滤"); sb.AppendLine(" query = GetDataPrivilege(\"a\",\"\",query);"); sb.AppendLine(" return await query.ToPageListAsync(pagination);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" public async Task<" + baseConfigModel.FileConfig.EntityName + $"> GetForm({idType} keyValue)"); sb.AppendLine(" {"); if (baseConfigModel.PageIndex.IsCache == false) { sb.AppendLine(" var data = await repository.FindEntity(keyValue);"); sb.AppendLine($" return data;"); } else { sb.AppendLine(" var data = await repository.CheckCache(cacheKey, keyValue);"); sb.AppendLine(" return data;"); } sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(); sb.AppendLine(" public async Task<" + baseConfigModel.FileConfig.EntityName + $"> GetLookForm({idType} keyValue)"); sb.AppendLine(" {"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" var data = await repository.CheckCache(cacheKey, keyValue);"); sb.AppendLine(" return GetFieldsFilterData(data);"); } else { sb.AppendLine(" var data = await repository.FindEntity(keyValue);"); sb.AppendLine(" return GetFieldsFilterData(data);"); } sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" #region 提交数据"); sb.AppendLine(" public async Task SubmitForm(" + baseConfigModel.FileConfig.EntityName + $" entity, {idType} keyValue" + (idType == "int" || idType == "long" ? "=0)" : ")")); sb.AppendLine(" {"); if (idType == "int" || idType == "long") { sb.AppendLine(" if(keyValue == 0)"); } else { sb.AppendLine(" if(string.IsNullOrEmpty(keyValue))"); } sb.AppendLine(" {"); sb.AppendLine(" //初始值添加"); if (!string.IsNullOrEmpty(baseConfigModel.PageIndex.DeleteColum)) { sb.AppendLine($" entity.{baseConfigModel.PageIndex.DeleteColum} = false;"); } foreach (var item in baseConfigModel.PageIndex.ColumnList) { if (item.field != idColumn && item.field != baseConfigModel.PageIndex.DeleteColum && item.field != baseConfigModel.PageIndex.CreateColum && !string.IsNullOrEmpty(item.value)) { sb.AppendLine($" entity.{item.field} = {item.value};"); } } if (string.IsNullOrEmpty(baseEntity)) { if (idType == "int") { sb.AppendLine(" entity." + idColumn + " = 0;"); } else if (idType == "long") { sb.AppendLine(" entity." + idColumn + " = 0;"); } else { sb.AppendLine(" entity." + idColumn + " = Utils.GuId();"); } if (!string.IsNullOrEmpty(baseConfigModel.PageIndex.CreateColum)) { sb.AppendLine($" entity.{baseConfigModel.PageIndex.CreateColum} = DateTime.Now;"); } } else { sb.AppendLine(" entity.Create();"); } sb.AppendLine(" await repository.Insert(entity);"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" await CacheHelper.Remove(cacheKey + \"list\");"); } sb.AppendLine(" }"); sb.AppendLine(" else"); sb.AppendLine(" {"); sb.AppendLine(" //此处需修改"); if (string.IsNullOrEmpty(baseEntity)) { if (idType == "int") { sb.AppendLine(" entity." + idColumn + " = Convert.ToInt32(keyValue);"); } else if (idType == "long") { sb.AppendLine(" entity." + idColumn + " = Convert.ToInt64(keyValue);"); } else { sb.AppendLine(" entity." + idColumn + " = keyValue;"); } } else { sb.AppendLine(" entity.Modify(keyValue); "); } sb.AppendLine(" await repository.Update(entity);"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" await CacheHelper.Remove(cacheKey + keyValue);"); sb.AppendLine(" await CacheHelper.Remove(cacheKey + \"list\");"); } sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" public async Task DeleteForm(string keyValue)"); sb.AppendLine(" {"); sb.AppendLine(" var ids = keyValue.Split(',');"); sb.AppendLine(" await repository.Delete(a => ids.Contains(a." + idColumn + ".ToString()));"); if (baseConfigModel.PageIndex.IsCache == true) { sb.AppendLine(" foreach (var item in ids)"); sb.AppendLine(" {"); sb.AppendLine(" await CacheHelper.Remove(cacheKey + item);"); sb.AppendLine(" }"); sb.AppendLine(" await CacheHelper.Remove(cacheKey + \"list\");"); } sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(); sb.AppendLine(" }"); sb.AppendLine("}"); return sb.ToString(); } #endregion BuildService #region BuildController public string BuildController(BaseConfigModel baseConfigModel, string idColumn = "F_Id", string idType = "string") { StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Threading.Tasks;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using Microsoft.AspNetCore.Mvc;"); sb.AppendLine("using HT.Cloud.Code;"); sb.AppendLine("using HT.Cloud.Domain." + baseConfigModel.OutputConfig.OutputModule + ";"); sb.AppendLine("using HT.Cloud.Service;"); sb.AppendLine("using Microsoft.AspNetCore.Authorization;"); sb.AppendLine("using HT.Cloud.Service." + baseConfigModel.OutputConfig.OutputModule + ";"); sb.AppendLine(); sb.AppendLine("namespace HT.Cloud.Web.Areas." + baseConfigModel.OutputConfig.OutputModule + ".Controllers"); sb.AppendLine("{"); SetClassDescription("控制器类", baseConfigModel, sb); sb.AppendLine(" [Area(\"" + baseConfigModel.OutputConfig.OutputModule + "\")]"); sb.AppendLine(" public class " + baseConfigModel.FileConfig.ControllerName + " : BaseController"); sb.AppendLine(" {"); sb.AppendLine(" public " + baseConfigModel.FileConfig.ServiceName + " _service {get;set;}"); sb.AppendLine(); sb.AppendLine(" #region 获取数据"); if (baseConfigModel.PageIndex.IsTree == true) { sb.AppendLine(" [HttpGet]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" public async Task GetTreeGridJson(string keyword)"); sb.AppendLine(" {"); sb.AppendLine(" var data = await _service.GetLookList(keyword);"); sb.AppendLine(" if (!string.IsNullOrEmpty(keyword))"); sb.AppendLine(" {"); sb.AppendLine(" //此处需修改"); sb.AppendLine(" data = data.TreeWhere(a => a." + baseConfigModel.PageIndex.TreeColum + ".Contains(keyword));"); sb.AppendLine(" }"); sb.AppendLine(" return Success(data.Count, data);"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" [HttpGet]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" public async Task GetTreeSelectJson()"); sb.AppendLine(" {"); sb.AppendLine(" var data = await _service.GetList();"); sb.AppendLine(" var treeList = new List();"); sb.AppendLine(" foreach (var item in data)"); sb.AppendLine(" {"); sb.AppendLine(" //此处需修改"); sb.AppendLine(" TreeSelectModel treeModel = new TreeSelectModel();"); sb.AppendLine(" treeModel.id = item." + idColumn + ";"); sb.AppendLine(" treeModel.text = item." + baseConfigModel.PageIndex.TreeColum + ";"); sb.AppendLine(" treeModel.parentId = item." + baseConfigModel.PageIndex.ParentColum + ";"); sb.AppendLine(" treeList.Add(treeModel);"); sb.AppendLine(" }"); sb.AppendLine(" return Content(treeList.TreeSelectJson());"); sb.AppendLine(" }"); } else { sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" [IgnoreAntiforgeryToken]"); sb.AppendLine(" public async Task GetGridJson(SoulPage<" + baseConfigModel.FileConfig.EntityName + "> pagination, string keyword)"); sb.AppendLine(" {"); sb.AppendLine(" if (string.IsNullOrEmpty(pagination.field))"); sb.AppendLine(" {"); sb.AppendLine($" pagination.field = \"{baseConfigModel.PageIndex.SortColumn}\";"); sb.AppendLine(" pagination.order = \"" + (baseConfigModel.PageIndex.IsAsc == true ? "asc" : "desc") + "\";"); sb.AppendLine(" }"); sb.AppendLine(" var data = await _service.GetLookList(pagination,keyword);"); sb.AppendLine(" return Content(pagination.setData(data).ToJson());"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" [HttpGet]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" public async Task GetListJson(string keyword)"); sb.AppendLine(" {"); sb.AppendLine(" var data = await _service.GetList(keyword);"); sb.AppendLine(" return Content(data.ToJson());"); sb.AppendLine(" }"); } sb.AppendLine(); sb.AppendLine(" [HttpGet]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine($" public async Task GetFormJson({idType} keyValue)"); sb.AppendLine(" {"); sb.AppendLine(" var data = await _service.GetLookForm(keyValue);"); sb.AppendLine(" return Content(data.ToJson());"); sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(); sb.AppendLine(" #region 提交数据"); sb.AppendLine(" [HttpPost]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" public async Task SubmitForm(" + baseConfigModel.FileConfig.EntityName + $" entity, {idType} keyValue)"); sb.AppendLine(" {"); sb.AppendLine(" try"); sb.AppendLine(" {"); sb.AppendLine(" await _service.SubmitForm(entity, keyValue);"); sb.AppendLine(" return await Success(\"操作成功。\", \"\", keyValue);"); sb.AppendLine(" }"); sb.AppendLine(" catch (Exception ex)"); sb.AppendLine(" {"); sb.AppendLine(" return await Error(ex.Message, \"\", keyValue);"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(" [HttpPost]"); sb.AppendLine(" [HandlerAjaxOnly]"); sb.AppendLine(" [HandlerAuthorize]"); sb.AppendLine(" public async Task DeleteForm(string keyValue)"); sb.AppendLine(" {"); sb.AppendLine(" try"); sb.AppendLine(" {"); sb.AppendLine(" await _service.DeleteForm(keyValue);"); sb.AppendLine(" return await Success(\"操作成功。\", \"\", keyValue, DbLogType.Delete);"); sb.AppendLine(" }"); sb.AppendLine(" catch (Exception ex)"); sb.AppendLine(" {"); sb.AppendLine(" return await Error(ex.Message, \"\", keyValue, DbLogType.Delete);"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine(" #endregion"); sb.AppendLine(" }"); sb.AppendLine("}"); return sb.ToString(); } #endregion BuildController #region BuildIndex public string BuildIndex(BaseConfigModel baseConfigModel, string idColumn = "F_Id") { #region 初始化集合 if (baseConfigModel.PageIndex.ButtonList == null) { baseConfigModel.PageIndex.ButtonList = new List(); } if (baseConfigModel.PageIndex.ColumnList == null) { baseConfigModel.PageIndex.ColumnList = new List(); } #endregion 初始化集合 List list = GetButtonAuthorizeList(); StringBuilder sb = new StringBuilder(); int buttonCount = baseConfigModel.PageIndex.ButtonList.Where(a => a != "add").Count(); sb.AppendLine("@{"); sb.AppendLine(" ViewBag.Title = \"Index\";"); sb.AppendLine(" Layout = \"~/Views/Shared/_Index.cshtml\";"); sb.AppendLine(" }"); sb.AppendLine("
"); sb.AppendLine("
"); #region 搜索栏 if (baseConfigModel.PageIndex.IsSearch == true) { sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); } #endregion 搜索栏 #region 工具栏 sb.AppendLine(" "); #endregion 工具栏 sb.AppendLine("
"); if (buttonCount > 0) { sb.AppendLine(" "); } sb.AppendLine(" "); sb.AppendLine(" "); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); #region js layui方法 sb.AppendLine(" "); #endregion js layui方法 return sb.ToString(); } #endregion BuildIndex #region BuildForm public string BuildForm(BaseConfigModel baseConfigModel) { #region 初始化集合 if (baseConfigModel.PageForm.FieldList == null) { baseConfigModel.PageForm.FieldList = new Dictionary(); } #endregion 初始化集合 StringBuilder sb = new StringBuilder(); sb.AppendLine("@{"); sb.AppendLine(" ViewBag.Title = \"Form\"; "); sb.AppendLine(" Layout = \"~/Views/Shared/_Form.cshtml\";"); sb.AppendLine("}"); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); #region 表单控件 if (baseConfigModel.PageForm.FieldList.Count > 0) { switch (baseConfigModel.PageForm.ShowMode) { case 1: foreach (var item in baseConfigModel.PageForm.FieldList) { sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); } break; case 2: int i = 1; foreach (var item in baseConfigModel.PageForm.FieldList) { if (i % 2 != 0) { sb.AppendLine("
"); } sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); if (i % 2 == 0) { sb.AppendLine("
"); } else if (i == baseConfigModel.PageForm.FieldList.Count) { sb.AppendLine("
"); } i++; } break; } } #endregion 表单控件 sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine(""); sb.AppendLine(""); return sb.ToString(); } #endregion BuildForm #region BuildDetails public string BuildDetails(BaseConfigModel baseConfigModel) { #region 初始化集合 if (baseConfigModel.PageForm.FieldList == null) { baseConfigModel.PageForm.FieldList = new Dictionary(); } #endregion 初始化集合 StringBuilder sb = new StringBuilder(); sb.AppendLine("@{"); sb.AppendLine(" ViewBag.Title = \"Details\"; "); sb.AppendLine(" Layout = \"~/Views/Shared/_Form.cshtml\";"); sb.AppendLine("}"); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine(""); sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine("
"); #region 表单控件 if (baseConfigModel.PageForm.FieldList.Count > 0) { switch (baseConfigModel.PageForm.ShowMode) { case 1: foreach (var item in baseConfigModel.PageForm.FieldList) { sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); } break; case 2: int i = 1; foreach (var item in baseConfigModel.PageForm.FieldList) { if (i % 2 != 0) { sb.AppendLine("
"); } sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine("
"); sb.AppendLine("
"); if (i % 2 == 0) { sb.AppendLine("
"); } else if (i == baseConfigModel.PageForm.FieldList.Count) { sb.AppendLine("
"); } i++; } break; } } #endregion 表单控件 sb.AppendLine("
"); sb.AppendLine("
"); sb.AppendLine(" "); sb.AppendLine(""); sb.AppendLine(""); return sb.ToString(); } #endregion BuildDetails #region BuildMenu public string BuildMenu(BaseConfigModel baseConfigModel, string idColumn = "F_Id") { StringBuilder sb = new StringBuilder(); sb.AppendLine(); sb.AppendLine(" 菜单路径:/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.PageIndexName); sb.AppendLine(); sb.AppendLine(" 主键:" + idColumn); List list = GetButtonAuthorizeList(); foreach (string btn in baseConfigModel.PageIndex.ButtonList) { KeyValue button = list.Where(p => p.Key == btn).First(); string form = ""; switch (btn) { case "delete": form = "DeleteForm"; break; case "details": form = "Details"; break; default: form = "Form"; break; } string url = "/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + form; sb.AppendLine(" 按钮名称:" + button.Description + ";编号:" + button.Value + ";事件:" + button.Key + ";连接:" + url); } sb.AppendLine(); return sb.ToString(); } #endregion BuildMenu #region CreateCode public async Task> CreateCode(BaseConfigModel baseConfigModel, string code) { List result = new List(); JObject param = code.ToJObject(); #region 集中判断 string codeIndex = ""; string indexPath = ""; if (!param["CodeIndex"].IsEmpty()) { codeIndex = HttpUtility.HtmlDecode(param["CodeIndex"].ToString()); indexPath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageIndexName + ".cshtml"); if (File.Exists(indexPath)) { throw new Exception("列表页已存在,列表页生成失败!"); } } string codeForm = ""; string formPath = ""; if (!param["CodeForm"].IsEmpty()) { codeForm = HttpUtility.HtmlDecode(param["CodeForm"].ToString()); formPath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageFormName + ".cshtml"); if (File.Exists(formPath)) { throw new Exception("表单页存在,表单页生成失败!"); } } string codeDetails = ""; string detailsPath = ""; if (!param["CodeDetails"].IsEmpty()) { codeDetails = HttpUtility.HtmlDecode(param["CodeDetails"].ToString()); detailsPath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Views", baseConfigModel.FileConfig.ClassPrefix, baseConfigModel.FileConfig.PageDetailsName + ".cshtml"); if (File.Exists(detailsPath)) { throw new Exception("详情页存在,详情页生成失败!"); } } string codeEntity = ""; string entityPath = ""; if (!string.IsNullOrEmpty(param["CodeEntity"].ParseToString())) { codeEntity = HttpUtility.HtmlDecode(param["CodeEntity"].ToString()); entityPath = Path.Combine(baseConfigModel.OutputConfig.OutputEntity, baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.EntityName + ".cs"); if (File.Exists(entityPath)) { throw new Exception("实体类已存在,实体类生成失败!"); } } string codeService = ""; string servicePath = ""; if (!param["CodeService"].IsEmpty()) { codeService = HttpUtility.HtmlDecode(param["CodeService"].ToString()); servicePath = Path.Combine(baseConfigModel.OutputConfig.OutputService, baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.ServiceName + ".cs"); if (File.Exists(servicePath)) { throw new Exception("服务类已存在,服务类生成失败!"); } } string codeController = ""; string controllerPath = ""; if (!param["CodeController"].IsEmpty()) { codeController = HttpUtility.HtmlDecode(param["CodeController"].ToString()); controllerPath = Path.Combine(baseConfigModel.OutputConfig.OutputWeb, "Areas", baseConfigModel.OutputConfig.OutputModule, "Controllers", baseConfigModel.FileConfig.ControllerName + ".cs"); if (File.Exists(controllerPath)) { throw new Exception("控制器已存在,控制器生成失败!"); } } #endregion 集中判断 #region 列表页 if (!param["CodeIndex"].IsEmpty()) { // 生成菜单,按钮 List buttonAuthorizeList = GetButtonAuthorizeList(); string menuUrl = "/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + baseConfigModel.FileConfig.PageIndexName; ModuleEntity moduleEntity = new ModuleEntity(); moduleEntity.Create(); moduleEntity.F_Layers = _context.Queryable().First(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule).F_Layers + 1; ; moduleEntity.F_FullName = baseConfigModel.FileConfig.ClassDescription; moduleEntity.F_UrlAddress = menuUrl; moduleEntity.F_EnCode = baseConfigModel.FileConfig.ClassPrefix; moduleEntity.F_IsExpand = false; moduleEntity.F_IsMenu = baseConfigModel.PageIndex.IsMunu == true ? true : false; moduleEntity.F_IsFields = baseConfigModel.PageIndex.IsFields == true ? true : false; moduleEntity.F_IsPublic = baseConfigModel.PageIndex.IsPublic == true ? true : false; moduleEntity.F_Target = "iframe"; moduleEntity.F_AllowEdit = false; moduleEntity.F_AllowDelete = false; moduleEntity.F_EnabledMark = true; moduleEntity.F_DeleteMark = false; moduleEntity.F_ParentId = _context.Queryable().First(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule).F_Id; var parentModule = await _context.Queryable().FirstAsync(a => a.F_EnCode == baseConfigModel.OutputConfig.OutputModule); moduleEntity.F_SortCode = (_context.Queryable().Where(a => a.F_ParentId == parentModule.F_Id).Max(a => a.F_SortCode) ?? 0) + 1; List moduleButtonList = new List(); int sort = 0; foreach (var item in baseConfigModel.PageIndex.ButtonList) { KeyValue button = buttonAuthorizeList.Where(p => p.Key == item).First(); string form = ""; switch (item) { case "delete": form = "DeleteForm"; break; case "details": form = "Details"; break; default: form = "Form"; break; } string url = "/" + baseConfigModel.OutputConfig.OutputModule + "/" + baseConfigModel.FileConfig.ClassPrefix + "/" + form; ModuleButtonEntity modulebutton = new ModuleButtonEntity(); modulebutton.Create(); modulebutton.F_ModuleId = moduleEntity.F_Id; modulebutton.F_ParentId = "0"; modulebutton.F_Layers = 1; modulebutton.F_EnCode = button.Value; modulebutton.F_JsEvent = button.Key; modulebutton.F_FullName = button.Description; modulebutton.F_Location = button.Key == "add" ? 1 : 2; modulebutton.F_SortCode = sort; sort++; modulebutton.F_EnabledMark = true; modulebutton.F_DeleteMark = false; modulebutton.F_Split = false; modulebutton.F_AllowDelete = false; modulebutton.F_AllowEdit = false; modulebutton.F_IsPublic = false; modulebutton.F_UrlAddress = url; moduleButtonList.Add(modulebutton); } List moduleFieldsList = new List(); foreach (var item in baseConfigModel.PageIndex.ColumnList) { ModuleFieldsEntity moduleFields = new ModuleFieldsEntity(); moduleFields.Create(); moduleFields.F_ModuleId = moduleEntity.F_Id; moduleFields.F_EnCode = item.field; moduleFields.F_FullName = item.title; moduleFields.F_IsPublic = true; moduleFields.F_EnabledMark = true; moduleFields.F_DeleteMark = false; moduleFieldsList.Add(moduleFields); } _context.Ado.BeginTran(); await _context.Insertable(moduleEntity).ExecuteCommandAsync(); await _context.Insertable(moduleButtonList).ExecuteCommandAsync(); if (moduleFieldsList.Count > 0) { await _context.Insertable(moduleFieldsList).ExecuteCommandAsync(); } _context.Ado.CommitTran(); await CacheHelper.RemoveAsync(authorizecacheKey + OperatorProvider.Provider.GetCurrent().DbNumber + "_list"); FileHelper.CreateFile(indexPath, codeIndex); result.Add(new KeyValue { Key = "列表页", Value = indexPath, Description = "生成成功!" }); } #endregion 列表页 #region 表单页 if (!param["CodeForm"].IsEmpty()) { FileHelper.CreateFile(formPath, codeForm); result.Add(new KeyValue { Key = "表单页", Value = formPath, Description = "生成成功!" }); } #endregion 表单页 #region 查看页 if (!param["CodeDetails"].IsEmpty()) { FileHelper.CreateFile(detailsPath, codeDetails); result.Add(new KeyValue { Key = "详情页", Value = detailsPath, Description = "生成成功!" }); } #endregion 查看页 #region 实体类 if (!string.IsNullOrEmpty(param["CodeEntity"].ParseToString())) { FileHelper.CreateFile(entityPath, codeEntity); result.Add(new KeyValue { Key = "实体类", Value = entityPath, Description = "生成成功!" }); } #endregion 实体类 #region 服务类 if (!param["CodeService"].IsEmpty()) { FileHelper.CreateFile(servicePath, codeService); result.Add(new KeyValue { Key = "服务类", Value = servicePath, Description = "生成成功!" }); } #endregion 服务类 #region 控制器 if (!param["CodeController"].IsEmpty()) { FileHelper.CreateFile(controllerPath, codeController); result.Add(new KeyValue { Key = "控制器", Value = controllerPath, Description = "生成成功!" }); } #endregion 控制器 return result; } #endregion CreateCode #region EntityCreateCode public async Task EntityCreateCode(BaseConfigModel baseConfigModel, string code) { await Task.Run(() => { string codeEntity = ""; string entityPath = ""; if (!string.IsNullOrEmpty(code)) { codeEntity = code; entityPath = Path.Combine(baseConfigModel.OutputConfig.OutputEntity, baseConfigModel.OutputConfig.OutputModule, baseConfigModel.FileConfig.EntityName + ".cs"); if (File.Exists(entityPath)) { throw new Exception("实体类已存在,实体类生成失败!"); } FileHelper.CreateFile(entityPath, codeEntity); } }); } #endregion EntityCreateCode #region 私有方法 #region GetProjectRootPath private string GetProjectRootPath(string path) { path = path.ParseToString(); path = path.Trim('\\'); if (GlobalContext.SystemConfig.Debug) { // 向上找一级 path = Directory.GetParent(path).FullName; //path = Directory.GetParent(path).FullName; } return path; } #endregion GetProjectRootPath #region SetClassDescription private void SetClassDescription(string type, BaseConfigModel baseConfigModel, StringBuilder sb) { sb.AppendLine(" /// "); sb.AppendLine(" /// 创 建:" + baseConfigModel.FileConfig.CreateUserName); sb.AppendLine(" /// 日 期:" + baseConfigModel.FileConfig.CreateDate); sb.AppendLine(" /// 描 述:" + baseConfigModel.FileConfig.ClassDescription + type); sb.AppendLine(" /// "); } #endregion SetClassDescription #region GetButtonAuthorizeList private List GetButtonAuthorizeList() { var list = new List(); list.Add(new KeyValue { Key = "add", Value = "NF-add", Description = "新增" }); list.Add(new KeyValue { Key = "edit", Value = "NF-edit", Description = "修改" }); list.Add(new KeyValue { Key = "delete", Value = "NF-delete", Description = "删除" }); list.Add(new KeyValue { Key = "details", Value = "NF-details", Description = "查看" }); return list; } #endregion GetButtonAuthorizeList private string GetBaseEntity(string EntityName, DataTable dt, string idColumn = "F_Id", bool keyIsNull = false) { string entity = string.Empty; var columnList = dt.AsEnumerable().Select(p => p["DbColumnName"].ParseToString()).ToList(); bool id = columnList.Where(p => p == idColumn).Any(); bool baseIsDelete = columnList.Where(p => p == "F_DeleteUserId").Any() && columnList.Where(p => p == "F_DeleteTime").Any() && columnList.Where(p => p == "F_DeleteMark").Any(); bool baseIsCreate = columnList.Where(p => p == "F_Id").Any() && columnList.Where(p => p == "F_CreatorUserId").Any() && columnList.Where(p => p == "F_CreatorTime").Any(); bool baseIsModifie = columnList.Where(p => p == "F_Id").Any() && columnList.Where(p => p == "F_LastModifyUserId").Any() && columnList.Where(p => p == "F_LastModifyTime").Any(); if (!id && !keyIsNull) { throw new Exception("数据库表必须有主键id字段"); } if (idColumn != "F_Id") { return null; } entity = "IEntity<" + EntityName + ">"; if (baseIsCreate) { entity += ",ICreationAudited"; } if (baseIsModifie) { entity += ",IModificationAudited"; } if (baseIsDelete) { entity += ",IDeleteAudited"; } return entity; } #endregion 私有方法 } }