开发代码生成自定义配置编辑

This commit is contained in:
izory 2021-09-18 16:10:34 +08:00
parent 30e1098a45
commit 8c8c205393
22 changed files with 573 additions and 267 deletions

View File

@ -11,6 +11,8 @@ namespace Infrastructure
public static string DbType = "DbType"; public static string DbType = "DbType";
public static string CodeGenDbType = "CodeGenDbType"; public static string CodeGenDbType = "CodeGenDbType";
public static string DbKey = "DbKey"; public static string DbKey = "DbKey";
public static string Gen_conn = "gen:conn";
public static string Gen_conn_dbType = "gen:dbType";
public string Conn_Admin { get; set; } public string Conn_Admin { get; set; }

View File

@ -6,6 +6,8 @@ using Microsoft.AspNetCore.Mvc;
using SqlSugar; using SqlSugar;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using ZR.Admin.WebApi.Extensions;
using ZR.Admin.WebApi.Filters; using ZR.Admin.WebApi.Filters;
using ZR.CodeGenerator; using ZR.CodeGenerator;
using ZR.CodeGenerator.CodeGenerator; using ZR.CodeGenerator.CodeGenerator;
@ -13,6 +15,7 @@ using ZR.CodeGenerator.Model;
using ZR.CodeGenerator.Service; using ZR.CodeGenerator.Service;
using ZR.Common; using ZR.Common;
using ZR.Model; using ZR.Model;
using ZR.Model.System.Dto;
using ZR.Model.System.Generate; using ZR.Model.System.Generate;
using ZR.Model.Vo; using ZR.Model.Vo;
using ZR.Service.System.IService; using ZR.Service.System.IService;
@ -90,12 +93,15 @@ namespace ZR.Admin.WebApi.Controllers
[ActionPermissionFilter(Permission = "tool:gen:code")] [ActionPermissionFilter(Permission = "tool:gen:code")]
public IActionResult Generate([FromBody] GenerateDto dto) public IActionResult Generate([FromBody] GenerateDto dto)
{ {
if (string.IsNullOrEmpty(dto.tableName)) if (string.IsNullOrEmpty(dto.tableName) || dto.TableId <= 0)
{ {
throw new CustomException(ResultCode.CUSTOM_ERROR, "请求参数为空"); throw new CustomException(ResultCode.CUSTOM_ERROR, "请求参数为空");
} }
var genTableInfo = GenTableService.GetGenTableInfo(dto.TableId);
var getTableColumn = GenTableColumnService.GenTableColumns(dto.TableId);
genTableInfo.Columns = getTableColumn;
DbTableInfo dbTableInfo = new() { Name = dto.tableName }; DbTableInfo dbTableInfo = new() { Name = dto.tableName };
CodeGeneratorTool.Generate(dbTableInfo, dto); CodeGeneratorTool.Generate(genTableInfo, dto);
return SUCCESS(dbTableInfo); return SUCCESS(dbTableInfo);
} }
@ -133,7 +139,7 @@ namespace ZR.Admin.WebApi.Controllers
} }
/// <summary> /// <summary>
/// 代码生成删除 /// 删除代码生成
/// </summary> /// </summary>
/// <param name="tableIds"></param> /// <param name="tableIds"></param>
/// <returns></returns> /// <returns></returns>
@ -143,8 +149,9 @@ namespace ZR.Admin.WebApi.Controllers
public IActionResult Remove(string tableIds) public IActionResult Remove(string tableIds)
{ {
long[] tableId = Tools.SpitLongArrary(tableIds); long[] tableId = Tools.SpitLongArrary(tableIds);
//TODO 带做 删除表
return SUCCESS(""); GenTableService.DeleteGenTableByIds(tableId);
return SUCCESS(1);
} }
/// <summary> /// <summary>
@ -165,53 +172,73 @@ namespace ZR.Admin.WebApi.Controllers
string[] tableNames = tables.Split(',', StringSplitOptions.RemoveEmptyEntries); string[] tableNames = tables.Split(',', StringSplitOptions.RemoveEmptyEntries);
string userName = User.Identity.Name; string userName = User.Identity.Name;
foreach (var item in tableNames) foreach (var tableName in tableNames)
{ {
var tabInfo = _CodeGeneraterService.GetTableInfo(dbName, item); var tabInfo = _CodeGeneraterService.GetTableInfo(dbName, tableName);
if (tabInfo != null) if (tabInfo != null)
{ {
GenTable genTable = new() GenTable genTable = new()
{ {
TableName = item, BaseNameSpace = "ZR.",
ModuleName = "bus",
ClassName = CodeGeneratorTool.GetClassName(tableName),
BusinessName = CodeGeneratorTool.GetClassName(tableName),
FunctionAuthor = ConfigUtils.Instance.GetConfig("gen:author"),
FunctionName = tabInfo.Description,
TableName = tableName,
TableComment = tabInfo.Description, TableComment = tabInfo.Description,
ClassName = CodeGeneratorTool.GetModelClassName(item), Create_by = userName,
CreateBy = userName,
CreateTime = DateTime.Now
}; };
int rows = GenTableService.InsertGenTable(genTable); int rows = GenTableService.ImportGenTable(genTable);
if (rows > 0) if (rows > 0)
{ {
//保存列信息 //保存列信息
List<DbColumnInfo> dbColumnInfos = _CodeGeneraterService.GetColumnInfo(dbName, item); List<DbColumnInfo> dbColumnInfos = _CodeGeneraterService.GetColumnInfo(dbName, tableName);
List<GenTableColumn> genTableColumns = new(); List<GenTableColumn> genTableColumns = new();
long tableId = 0;
foreach (var column in dbColumnInfos) foreach (var column in dbColumnInfos)
{ {
tableId = column.TableId;
GenTableColumn genTableColumn = new() GenTableColumn genTableColumn = new()
{ {
ColumnName = column.DbColumnName, ColumnName = CodeGeneratorTool.FirstLowerCase(column.DbColumnName),
ColumnComment = column.ColumnDescription, ColumnComment = column.ColumnDescription,
IsPk = column.IsPrimarykey, IsPk = column.IsPrimarykey,
ColumnType = column.DataType, ColumnType = column.DataType,
TableId = rows, TableId = rows,
TableName = item, TableName = tableName,
CsharpType = TableMappingHelper.GetPropertyDatatype(column.DataType), CsharpType = TableMappingHelper.GetPropertyDatatype(column.DataType),
CsharpField = column.DbColumnName.Substring(0, 1).ToUpper() + column.DbColumnName[1..], CsharpField = column.DbColumnName.Substring(0, 1).ToUpper() + column.DbColumnName[1..],
IsRequired = column.IsNullable, IsRequired = column.IsNullable,
IsIncrement = column.IsIdentity, IsIncrement = column.IsIdentity,
CreateBy = userName, Create_by = userName,
CreateTime = DateTime.Now, Create_time = DateTime.Now,
IsInsert = true, IsInsert = true,
IsEdit = true, IsEdit = true,
IsList = true, IsList = true,
IsQuery = false IsQuery = false,
HtmlType = GenConstants.HTML_INPUT
}; };
if (CodeGeneratorTool.imageFiled.Any(f => column.DbColumnName.ToLower().Contains(f.ToLower())))
{
genTableColumn.HtmlType = GenConstants.HTML_IMAGE_UPLOAD;
}
if (genTableColumn.CsharpType.ToLower().Contains("datetime"))
{
genTableColumn.HtmlType = GenConstants.HTML_DATETIME;
}
if (CodeGeneratorTool.radioFiled.Any(f => column.DbColumnName.Contains(f)))
{
genTableColumn.HtmlType = GenConstants.HTML_RADIO;
}
if (column.Length > 200)
{
genTableColumn.HtmlType = GenConstants.HTML_TEXTAREA;
}
genTableColumns.Add(genTableColumn); genTableColumns.Add(genTableColumn);
} }
GenTableColumnService.DeleteGenTableColumn(tableId); GenTableColumnService.DeleteGenTableColumnByTableName(tableName);
GenTableColumnService.InsertGenTableColumn(genTableColumns); GenTableColumnService.InsertGenTableColumn(genTableColumns);
} }
} }
@ -219,5 +246,25 @@ namespace ZR.Admin.WebApi.Controllers
return SUCCESS(1); return SUCCESS(1);
} }
/// <summary>
/// 代码生成保存
/// </summary>
/// <returns></returns>
[HttpPut()]
//[Log(Title = "代码生成", BusinessType = BusinessType.UPDATE)]
[ActionPermissionFilter(Permission = "tool:gen:edit")]
public IActionResult EditSave([FromBody]GenTableDto genTableDto)
{
if (genTableDto == null) throw new CustomException("请求参数错误");
var genTable = genTableDto.Adapt<GenTable>().ToUpdate();
int rows = GenTableService.UpdateGenTable(genTable);
if (rows > 0)
{
GenTableColumnService.UpdateGenTableColumn(genTable.Columns);
}
return SUCCESS(rows);
}
} }
} }

View File

@ -49,27 +49,27 @@ namespace ZR.Admin.WebApi.Extensions
return source; return source;
} }
//public static TSource ToUpdate<TSource>(this TSource source, UserSessionVM userSession) public static TSource ToUpdate<TSource>(this TSource source, HttpContext context = null)
//{ {
// var types = source.GetType(); var types = source.GetType();
// if (types.GetProperty("UpdateTime") != null) if (types.GetProperty("UpdateTime") != null)
// { {
// types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null); types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null);
// } }
//if (types.GetProperty("UpdateID") != null) //if (types.GetProperty("UpdateID") != null)
//{ //{
// types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null); // types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null);
//} //}
// if (types.GetProperty("UpdateName") != null) if (types.GetProperty("UpdateBy") != null)
// { {
// types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null); types.GetProperty("UpdateBy").SetValue(source,context.GetName(), null);
// } }
// return source; return source;
//} }
} }
} }

View File

@ -49,6 +49,6 @@ namespace ZR.CodeGenerator
/// <summary> /// <summary>
/// 要生数据的表,用“,”分割 /// 要生数据的表,用“,”分割
/// </summary> /// </summary>
public string TableList { get; set; } //public string TableList { get; set; }
} }
} }

View File

@ -5,6 +5,7 @@ using System.Linq;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using ZR.CodeGenerator.CodeGenerator; using ZR.CodeGenerator.CodeGenerator;
using ZR.Model.System.Generate;
namespace ZR.CodeGenerator namespace ZR.CodeGenerator
{ {
@ -20,11 +21,11 @@ namespace ZR.CodeGenerator
/// </summary> /// </summary>
/// <param name="dbColumnInfo"></param> /// <param name="dbColumnInfo"></param>
/// <returns></returns> /// <returns></returns>
public static string GetVueJsMethod(DbColumnInfo dbColumnInfo) public static string GetVueJsMethod(GenTableColumn dbColumnInfo)
{ {
string columnName = CodeGeneratorTool.FirstLowerCase(dbColumnInfo.DbColumnName); string columnName = dbColumnInfo.ColumnName;
string js = ""; string js = "";
if (CodeGeneratorTool.imageFiled.Any(f => columnName.Contains(f))) if (dbColumnInfo.HtmlType.Equals(GenConstants.HTML_IMAGE_UPLOAD))
{ {
js += $"handleUpload{columnName}Success(res, file) {{\n"; js += $"handleUpload{columnName}Success(res, file) {{\n";
js += $" this.form.{columnName} = URL.createObjectURL(file.raw);\n"; js += $" this.form.{columnName} = URL.createObjectURL(file.raw);\n";
@ -35,21 +36,20 @@ namespace ZR.CodeGenerator
} }
//rules //rules
public static string GetFormRules(DbColumnInfo dbFieldInfo) public static string GetFormRules(GenTableColumn dbFieldInfo)
{ {
string vueViewEditFromRuleContent = ""; string vueViewEditFromRuleContent = "";
//Rule 规则验证 //Rule 规则验证
if (!dbFieldInfo.IsNullable && !dbFieldInfo.IsIdentity) if (!dbFieldInfo.IsPk && !dbFieldInfo.IsIncrement)
{ {
vueViewEditFromRuleContent += $" {dbFieldInfo.DbColumnName}: [\n"; vueViewEditFromRuleContent += $" {dbFieldInfo.ColumnName}: [\n";
vueViewEditFromRuleContent += $" {{ required: true, message: '请输入{dbFieldInfo.ColumnDescription}', trigger: \"blur\"}},\n"; vueViewEditFromRuleContent += $" {{ required: true, message: '请输入{dbFieldInfo.ColumnComment}', trigger: \"blur\"}},\n";
//vueViewEditFromRuleContent += " { min: 2, max: 50, message: \"长度在 2 到 50 个字符\", trigger:\"blur\" }\n";
vueViewEditFromRuleContent += " ],\n"; vueViewEditFromRuleContent += " ],\n";
} }
else if (TableMappingHelper.IsNumber(dbFieldInfo.DataType)) else if (TableMappingHelper.IsNumber(dbFieldInfo.ColumnType) && dbFieldInfo.IsRequired)
{ {
vueViewEditFromRuleContent += $" {dbFieldInfo.DbColumnName}: [\n"; vueViewEditFromRuleContent += $" {dbFieldInfo.ColumnName}: [\n";
vueViewEditFromRuleContent += $" {{ type: 'number', message: '{dbFieldInfo.DbColumnName}必须为数字值', trigger: \"blur\"}},\n"; vueViewEditFromRuleContent += $" {{ type: 'number', message: '{dbFieldInfo.ColumnName}必须为数字值', trigger: \"blur\"}},\n";
vueViewEditFromRuleContent += " ],\n"; vueViewEditFromRuleContent += " ],\n";
} }
@ -57,49 +57,49 @@ namespace ZR.CodeGenerator
} }
//model 属性 //model 属性
public static string GetModelTemplate(DbColumnInfo dbFieldInfo) public static string GetModelTemplate(GenTableColumn dbFieldInfo)
{ {
string columnName = dbFieldInfo.DbColumnName.Substring(0, 1).ToUpper() + dbFieldInfo.DbColumnName[1..];
var modelcontent = ""; var modelcontent = "";
modelcontent += " /// <summary>\n"; modelcontent += " /// <summary>\n";
modelcontent += $" /// 描述 :{dbFieldInfo.ColumnDescription}\n"; modelcontent += $" /// 描述 :{dbFieldInfo.ColumnComment}\n";
modelcontent += $" /// 空值 :{dbFieldInfo.IsNullable}\n"; modelcontent += $" /// 空值 :{dbFieldInfo.IsRequired}\n";
modelcontent += $" /// 默认 :{dbFieldInfo.DefaultValue}\n";
modelcontent += " /// </summary>\n"; modelcontent += " /// </summary>\n";
if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey) if (dbFieldInfo.IsPk || dbFieldInfo.IsIncrement)
{ {
modelcontent += $" [SqlSugar.SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPrimarykey.ToString().ToLower()}, IsIdentity = {dbFieldInfo.IsIdentity.ToString().ToLower()})]\n"; modelcontent += $" [SqlSugar.SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPk.ToString().ToLower()}, IsIdentity = {dbFieldInfo.IsIncrement.ToString().ToLower()})]\n";
} }
modelcontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r"; modelcontent += $" public {dbFieldInfo.CsharpType} {dbFieldInfo.CsharpField} {{ get; set; }}\n\r";
return modelcontent; return modelcontent;
} }
//DTO model //DTO model
public static string GetDtoContent(DbColumnInfo dbFieldInfo) public static string GetDtoContent(GenTableColumn dbFieldInfo)
{ {
string columnName = dbFieldInfo.DbColumnName.Substring(0, 1).ToUpper() + dbFieldInfo.DbColumnName[1..];
string InputDtoContent = ""; string InputDtoContent = "";
InputDtoContent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r"; if (dbFieldInfo.IsInsert || dbFieldInfo.IsEdit)
{
InputDtoContent += $" public {dbFieldInfo.CsharpType} {dbFieldInfo.CsharpField} {{ get; set; }}\n\r";
}
return InputDtoContent; return InputDtoContent;
} }
//form-item //form-item
public static string GetVueViewFormContent(DbColumnInfo dbFieldInfo) public static string GetVueViewFormContent(GenTableColumn dbFieldInfo)
{ {
string columnName = CodeGeneratorTool.FirstLowerCase(dbFieldInfo.DbColumnName); string columnName = dbFieldInfo.ColumnName;
string labelName = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName); string labelName = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnComment, columnName);
string vueViewFromContent = ""; string vueViewFromContent = "";
string labelDisabled = dbFieldInfo.IsIdentity ? ":disabled=\"true\"" : ""; string labelDisabled = dbFieldInfo.IsPk ? ":disabled=\"true\"" : "";
string placeHolder = dbFieldInfo.IsIdentity ? "" : $"请输入{CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName)}"; string placeHolder = dbFieldInfo.IsIncrement ? "" : $"请输入{labelName}";
if (dbFieldInfo.DataType == "datetime") if (dbFieldInfo.HtmlType == GenConstants.HTML_DATETIME)
{ {
//时间 //时间
vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\n"; vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\n";
vueViewFromContent += $" <el-date-picker v-model=\"form.{columnName}\" type=\"datetime\" placeholder=\"选择日期时间\" default-time=\"12:00:00\"> </el-date-picker>\n"; vueViewFromContent += $" <el-date-picker v-model=\"form.{columnName}\" type=\"datetime\" placeholder=\"选择日期时间\" default-time=\"12:00:00\"> </el-date-picker>\n";
vueViewFromContent += " </el-form-item>\n"; vueViewFromContent += " </el-form-item>\n";
} }
else if (CodeGeneratorTool.imageFiled.Any(f => columnName.Contains(f))) else if (dbFieldInfo.HtmlType == GenConstants.HTML_IMAGE_UPLOAD)
{ {
//图片 //图片
vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\n"; vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\n";
@ -110,7 +110,7 @@ namespace ZR.CodeGenerator
vueViewFromContent += $" <el-input v-model=\"form.{columnName}\" placeholder=\"请上传文件或手动输入文件地址\"></el-input>\n"; vueViewFromContent += $" <el-input v-model=\"form.{columnName}\" placeholder=\"请上传文件或手动输入文件地址\"></el-input>\n";
vueViewFromContent += " </el-form-item>\n"; vueViewFromContent += " </el-form-item>\n";
} }
else if (CodeGeneratorTool.radioFiled.Any(f => columnName.Contains(f)) && (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint" || dbFieldInfo.DataType == "int")) else if (dbFieldInfo.HtmlType == GenConstants.HTML_RADIO)
{ {
vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\n"; vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\n";
vueViewFromContent += $" <el-radio-group v-model=\"form.{columnName}\">\n"; vueViewFromContent += $" <el-radio-group v-model=\"form.{columnName}\">\n";
@ -119,10 +119,16 @@ namespace ZR.CodeGenerator
vueViewFromContent += " </el-radio-group>\n"; vueViewFromContent += " </el-radio-group>\n";
vueViewFromContent += " </el-form-item>\n"; vueViewFromContent += " </el-form-item>\n";
} }
else if (dbFieldInfo.HtmlType == GenConstants.HTML_TEXTAREA)
{
vueViewFromContent += $" <el-form-item label=\"{ labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\n";
vueViewFromContent += $" <el-input type=\"textarea\" v-model=\"form.{columnName}\" placeholder=\"请输入内容\"/>\n";
vueViewFromContent += " </el-form-item>\n";
}
else else
{ {
string inputNumTxt = TableMappingHelper.IsNumber(dbFieldInfo.DataType) ? ".number" : ""; string inputNumTxt = TableMappingHelper.IsNumber(dbFieldInfo.CsharpType) ? ".number" : "";
vueViewFromContent += $" <el-form-item label=\"{ CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" :label-width=\"labelWidth\" prop=\"{CodeGeneratorTool.FirstLowerCase(columnName)}\">\n"; vueViewFromContent += $" <el-form-item label=\"{ labelName}\" :label-width=\"labelWidth\" prop=\"{CodeGeneratorTool.FirstLowerCase(columnName)}\">\n";
vueViewFromContent += $" <el-input v-model{inputNumTxt}=\"form.{CodeGeneratorTool.FirstLowerCase(columnName)}\" placeholder=\"{placeHolder}\" {labelDisabled}/>\n"; vueViewFromContent += $" <el-input v-model{inputNumTxt}=\"form.{CodeGeneratorTool.FirstLowerCase(columnName)}\" placeholder=\"{placeHolder}\" {labelDisabled}/>\n";
vueViewFromContent += " </el-form-item>\n"; vueViewFromContent += " </el-form-item>\n";
} }
@ -131,14 +137,18 @@ namespace ZR.CodeGenerator
} }
//table-column //table-column
public static string GetTableColumn(DbColumnInfo dbFieldInfo) public static string GetTableColumn(GenTableColumn dbFieldInfo)
{ {
string columnName = CodeGeneratorTool.FirstLowerCase(dbFieldInfo.DbColumnName); string columnName = dbFieldInfo.ColumnName;
string label = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName); string label = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnComment, columnName);
string vueViewListContent = ""; string vueViewListContent = "";
string showToolTip = dbFieldInfo.DataType.Contains("varchar") ? ":show-overflow-tooltip=\"true\"" : ""; string showToolTip = dbFieldInfo.ColumnType.Contains("varchar") ? ":show-overflow-tooltip=\"true\"" : "";
if (!dbFieldInfo.IsQuery)
{
return vueViewListContent;
}
if (CodeGeneratorTool.imageFiled.Any(f => columnName.ToLower().Contains(f))) if (dbFieldInfo.HtmlType.Equals(GenConstants.HTML_IMAGE_UPLOAD))
{ {
vueViewListContent += $" <el-table-column prop=\"{ columnName}\" label=\"图片\">\n"; vueViewListContent += $" <el-table-column prop=\"{ columnName}\" label=\"图片\">\n";
vueViewListContent += " <template slot-scope=\"scope\">\n"; vueViewListContent += " <template slot-scope=\"scope\">\n";
@ -146,19 +156,19 @@ namespace ZR.CodeGenerator
vueViewListContent += " </template>\n"; vueViewListContent += " </template>\n";
vueViewListContent += " </el-table-column>\n"; vueViewListContent += " </el-table-column>\n";
} }
else if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint") //else if (dbFieldInfo.HtmlType.Equals(GenConstants.HTML_RADIO))
{ //{
vueViewListContent += $" <el-table-column prop=\"{columnName}\" label=\"{label}\" width=\"120\" >\n"; // vueViewListContent += $" <el-table-column prop=\"{columnName}\" label=\"{label}\" width=\"120\" >\n";
vueViewListContent += " <template slot-scope=\"scope\">\n"; // vueViewListContent += " <template slot-scope=\"scope\">\n";
vueViewListContent += $" <el-tag :type=\"scope.row.{columnName} === true ? 'success' : 'info'\" disable-transitions >"; // vueViewListContent += $" <el-tag :type=\"scope.row.{columnName} === true ? 'success' : 'info'\" disable-transitions >";
vueViewListContent += $" {{scope.row.{columnName}===true?'启用':'禁用'}} </el-tag>\n"; // vueViewListContent += $" {{scope.row.{columnName}===true?'启用':'禁用'}} </el-tag>\n";
vueViewListContent += " </template>\n"; // vueViewListContent += " </template>\n";
vueViewListContent += " </el-table-column>\n"; // vueViewListContent += " </el-table-column>\n";
} //}
else else
{ {
//table-column //table-column
vueViewListContent += $" <el-table-column prop=\"{CodeGeneratorTool.FirstLowerCase(columnName)}\" label=\"{CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" align=\"center\" width=\"100\" {showToolTip} />\n"; vueViewListContent += $" <el-table-column prop=\"{CodeGeneratorTool.FirstLowerCase(columnName)}\" label=\"{label}\" align=\"center\" width=\"100\" {showToolTip} />\n";
} }
return vueViewListContent; return vueViewListContent;
} }

View File

@ -1,10 +1,12 @@
using SqlSugar; using Infrastructure;
using SqlSugar;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using ZR.CodeGenerator.Model; using ZR.CodeGenerator.Model;
using ZR.CodeGenerator.Service; using ZR.CodeGenerator.Service;
using ZR.Model.System.Generate;
namespace ZR.CodeGenerator namespace ZR.CodeGenerator
{ {
@ -33,7 +35,7 @@ namespace ZR.CodeGenerator
/// </summary> /// </summary>
/// <param name="dbTableInfo"></param> /// <param name="dbTableInfo"></param>
/// <param name="dto"></param> /// <param name="dto"></param>
public static void Generate(DbTableInfo dbTableInfo, GenerateDto dto) public static void Generate(GenTable dbTableInfo, GenerateDto dto)
{ {
_option.BaseNamespace = "ZR."; _option.BaseNamespace = "ZR.";
//_option.TableList = listTable; //_option.TableList = listTable;
@ -46,9 +48,9 @@ namespace ZR.CodeGenerator
_option.ServicesNamespace = _option.BaseNamespace + "Service"; _option.ServicesNamespace = _option.BaseNamespace + "Service";
_option.ApiControllerNamespace = _option.BaseNamespace + "Admin.WebApi"; _option.ApiControllerNamespace = _option.BaseNamespace + "Admin.WebApi";
CodeGeneraterService codeGeneraterService = new(); //CodeGeneraterService codeGeneraterService = new();
List<DbColumnInfo> listField = codeGeneraterService.GetColumnInfo(dto.dbName, dbTableInfo.Name); //List<DbColumnInfo> listField = codeGeneraterService.GetColumnInfo(dto.dbName, dbTableInfo.TableName);
GenerateSingle(listField, dbTableInfo, dto); GenerateSingle(dbTableInfo?.Columns, dbTableInfo, dto);
//GenerateDtoProfile(_option.ModelsNamespace, profileContent, ifExsitedCovered); //GenerateDtoProfile(_option.ModelsNamespace, profileContent, ifExsitedCovered);
} }
@ -59,9 +61,9 @@ namespace ZR.CodeGenerator
/// <param name="listField">表字段集合</param> /// <param name="listField">表字段集合</param>
/// <param name="tableInfo">表信息</param> /// <param name="tableInfo">表信息</param>
/// <param name="dto"></param> /// <param name="dto"></param>
public static void GenerateSingle(List<DbColumnInfo> listField, DbTableInfo tableInfo, GenerateDto dto) public static void GenerateSingle(List<GenTableColumn> listField, GenTable tableInfo, GenerateDto dto)
{ {
var modelTypeName = GetModelClassName(tableInfo.Name);//表名对应C# 实体类名 var modelTypeName = tableInfo.ClassName;//表名对应C# 实体类名
var primaryKey = "id";//主键 var primaryKey = "id";//主键
string keyTypeName = "int";//主键数据类型 string keyTypeName = "int";//主键数据类型
@ -77,26 +79,24 @@ namespace ZR.CodeGenerator
string vueViewEditFromRuleContent = string.Empty;//Vue数据校验 string vueViewEditFromRuleContent = string.Empty;//Vue数据校验
string vueJsMethod = string.Empty;//Vue js自定义方法 string vueJsMethod = string.Empty;//Vue js自定义方法
foreach (DbColumnInfo dbFieldInfo in listField) foreach (GenTableColumn dbFieldInfo in listField)
{ {
string columnName = FirstLowerCase(dbFieldInfo.DbColumnName); string columnName = dbFieldInfo.ColumnName;
if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint") if (dbFieldInfo.ColumnType == "bool" || dbFieldInfo.ColumnType == "tinyint")
{ {
vueViewEditFromContent += $" {columnName}: 'true',\n"; vueViewEditFromContent += $" {columnName}: 'true',\n";
//vueViewEditFromBindContent += $" this.form.{columnName} = res.data.{0}+''\n";
} }
else else
{ {
vueViewEditFromContent += $" {columnName}: undefined,\n"; vueViewEditFromContent += $" {columnName}: undefined,\n";
//vueViewEditFromBindContent += $" {columnName}: row.{columnName},\n";
} }
//vueViewSaveBindContent += string.Format(" '{0}':this.editFrom.{0},\n", columnName); //vueViewSaveBindContent += string.Format(" '{0}':this.editFrom.{0},\n", columnName);
//主键 //主键
if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey) if (dbFieldInfo.IsPk || dbFieldInfo.IsIncrement)
{ {
primaryKey = columnName.Substring(0, 1).ToUpper() + columnName[1..]; primaryKey = columnName.Substring(0, 1).ToUpper() + columnName[1..];
keyTypeName = dbFieldInfo.DataType; keyTypeName = dbFieldInfo.CsharpType;
} }
else else
{ {
@ -104,7 +104,6 @@ namespace ZR.CodeGenerator
updateColumn += $" {tempColumnName} = parm.{tempColumnName},\n"; updateColumn += $" {tempColumnName} = parm.{tempColumnName},\n";
} }
dbFieldInfo.DbColumnName = columnName;
modelContent += CodeGenerateTemplate.GetModelTemplate(dbFieldInfo); modelContent += CodeGenerateTemplate.GetModelTemplate(dbFieldInfo);
vueViewFormContent += CodeGenerateTemplate.GetVueViewFormContent(dbFieldInfo); vueViewFormContent += CodeGenerateTemplate.GetVueViewFormContent(dbFieldInfo);
vueJsMethod += CodeGenerateTemplate.GetVueJsMethod(dbFieldInfo); vueJsMethod += CodeGenerateTemplate.GetVueJsMethod(dbFieldInfo);
@ -117,8 +116,8 @@ namespace ZR.CodeGenerator
replaceDto.PrimaryKey = primaryKey; replaceDto.PrimaryKey = primaryKey;
replaceDto.ModelTypeName = modelTypeName; replaceDto.ModelTypeName = modelTypeName;
replaceDto.ModelProperty = modelContent; replaceDto.ModelProperty = modelContent;
replaceDto.TableName = tableInfo.Name; replaceDto.TableName = tableInfo.TableName;
replaceDto.TableDesc = tableInfo.Description; replaceDto.TableDesc = tableInfo.TableComment;
replaceDto.InputDtoProperty = InputDtoContent; replaceDto.InputDtoProperty = InputDtoContent;
replaceDto.updateColumn = updateColumn; replaceDto.updateColumn = updateColumn;
replaceDto.VueJsMethod = vueJsMethod; replaceDto.VueJsMethod = vueJsMethod;
@ -407,19 +406,29 @@ namespace ZR.CodeGenerator
/// <summary> /// <summary>
/// 如果有前缀替换将前缀替换成空,替换下划线"_"为空再将首字母大写 /// 如果有前缀替换将前缀替换成空,替换下划线"_"为空再将首字母大写
/// 表名转换成C#类名
/// </summary> /// </summary>
/// <param name="modelTypeName"></param> /// <param name="tableName"></param>
/// <returns></returns> /// <returns></returns>
public static string GetModelClassName(string modelTypeName) public static string GetClassName(string tableName)
{ {
if (!string.IsNullOrEmpty(_option.ReplaceTableNameStr)) bool autoRemovePre = ConfigUtils.Instance.GetAppConfig("gen:autoPre", false);
string tablePrefix = ConfigUtils.Instance.GetAppConfig<string>("gen:tablePrefix");
if (!string.IsNullOrEmpty(tablePrefix) && autoRemovePre)
{ {
modelTypeName = modelTypeName.Replace(_option.ReplaceTableNameStr.ToString(), ""); string[] searcList = tablePrefix.Split(",",StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < searcList.Length; i++)
{
if (!string.IsNullOrEmpty(searcList[i].ToString()))
{
tableName = tableName.Replace(searcList[i].ToString(), "");
} }
modelTypeName = modelTypeName.Replace("_", "");
modelTypeName = modelTypeName.Substring(0, 1).ToUpper() + modelTypeName[1..];
return modelTypeName;
} }
}
return tableName.Substring(0, 1).ToUpper() + tableName[1..].Replace("_", "");
}
/// <summary> /// <summary>
/// 首字母转小写,输出前端 /// 首字母转小写,输出前端
/// </summary> /// </summary>

View File

@ -19,8 +19,8 @@ namespace ZR.CodeGenerator
/// <returns></returns> /// <returns></returns>
public SqlSugarScope GetSugarDbContext(string dbName = "") public SqlSugarScope GetSugarDbContext(string dbName = "")
{ {
string connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.Conn).Replace("{database}", dbName); string connStr = ConfigUtils.Instance.GetConfig(OptionsSetting.Gen_conn).Replace("{database}", dbName);
int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.CodeGenDbType, 0); int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.Gen_conn_dbType, 0);
if (string.IsNullOrEmpty(dbName)) if (string.IsNullOrEmpty(dbName))
{ {
connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.ConnAdmin); connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.ConnAdmin);

View File

@ -0,0 +1,119 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ZR.CodeGenerator
{
/// <summary>
/// 代码生成常量
/// </summary>
public class GenConstants
{
/** 单表(增删改查) */
public static string TPL_CRUD = "crud";
/** 树表(增删改查) */
public static string TPL_TREE = "tree";
/** 主子表(增删改查) */
public static string TPL_SUB = "sub";
/** 树编码字段 */
public static string TREE_CODE = "treeCode";
/** 树父编码字段 */
public static string TREE_PARENT_CODE = "treeParentCode";
/** 树名称字段 */
public static string TREE_NAME = "treeName";
/** 上级菜单ID字段 */
public static string PARENT_MENU_ID = "parentMenuId";
/** 上级菜单名称字段 */
public static string PARENT_MENU_NAME = "parentMenuName";
/** 数据库字符串类型 */
public static string[] COLUMNTYPE_STR = { "char", "varchar", "nvarchar", "varchar2" };
/** 数据库文本类型 */
public static string[] COLUMNTYPE_TEXT = { "tinytext", "text", "mediumtext", "longtext" };
/** 数据库时间类型 */
public static string[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" };
/** 数据库数字类型 */
public static string[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer",
"bit", "bigint", "float", "double", "decimal" };
/** 页面不需要编辑字段 */
public static string[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" };
/** 页面不需要显示的列表字段 */
public static string[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time" };
/** 页面不需要查询字段 */
public static string[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by",
"update_time", "remark" };
/** Entity基类字段 */
public static string[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" };
/** Tree基类字段 */
public static string[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors", "children" };
/** 文本框 */
public static string HTML_INPUT = "input";
/** 文本域 */
public static string HTML_TEXTAREA = "textarea";
/** 下拉框 */
public static string HTML_SELECT = "select";
/** 单选框 */
public static string HTML_RADIO = "radio";
/** 复选框 */
public static string HTML_CHECKBOX = "checkbox";
/** 日期控件 */
public static string HTML_DATETIME = "datetime";
/** 图片上传控件 */
public static string HTML_IMAGE_UPLOAD = "imageUpload";
/** 文件上传控件 */
public static string HTML_FILE_UPLOAD = "fileUpload";
/** 富文本控件 */
public static string HTML_EDITOR = "editor";
/** 字符串类型 */
public static string TYPE_STRING = "string";
/** 整型 */
public static string TYPE_INTEGER = "Integer";
/** 长整型 */
public static string TYPE_LONG = "Long";
/** 浮点型 */
public static string TYPE_DOUBLE = "Double";
/** 高精度计算类型 */
public static string TYPE_BIGDECIMAL = "BigDecimal";
/** 时间类型 */
public static string TYPE_DATE = "Date";
/** 模糊查询 */
public static string QUERY_LIKE = "LIKE";
/** 需要 */
public static string REQUIRE = "1";
}
}

View File

@ -8,6 +8,7 @@ namespace ZR.CodeGenerator.Model
{ {
public class GenerateDto public class GenerateDto
{ {
public long TableId { get; set; }
public string[] queryColumn { get; set; } public string[] queryColumn { get; set; }
/// <summary> /// <summary>
/// ///

View File

@ -55,45 +55,45 @@ namespace ZR.CodeGenerator.CodeGenerator
case "number": case "number":
case "integer": case "integer":
case "smallint": case "smallint":
sTempDatatype = "int?"; sTempDatatype = "int";
break; break;
case "bigint": case "bigint":
sTempDatatype = "long?"; sTempDatatype = "long";
break; break;
case "tinyint": case "tinyint":
sTempDatatype = "byte?"; sTempDatatype = "byte";
break; break;
case "numeric": case "numeric":
case "real": case "real":
sTempDatatype = "Single?"; sTempDatatype = "Single";
break; break;
case "float": case "float":
sTempDatatype = "float?"; sTempDatatype = "float";
break; break;
case "decimal": case "decimal":
case "numer(8,2)": case "numer(8,2)":
sTempDatatype = "decimal?"; sTempDatatype = "decimal";
break; break;
case "bit": case "bit":
sTempDatatype = "bool?"; sTempDatatype = "bool";
break; break;
case "date": case "date":
case "datetime": case "datetime":
case "datetime2": case "datetime2":
case "smalldatetime": case "smalldatetime":
sTempDatatype = "DateTime?"; sTempDatatype = "DateTime";
break; break;
case "money": case "money":
case "smallmoney": case "smallmoney":
sTempDatatype = "double?"; sTempDatatype = "double";
break; break;
case "char": case "char":
@ -113,7 +113,7 @@ namespace ZR.CodeGenerator.CodeGenerator
public static bool IsNumber(string tableDataType) public static bool IsNumber(string tableDataType)
{ {
string[] arr = new string[] { "int", "long" }; string[] arr = new string[] { "int", "long" };
return arr.Any(f => f.Replace("?", "").Contains(GetPropertyDatatype(tableDataType))); return arr.Any(f => f.Contains(GetPropertyDatatype(tableDataType)));
} }
} }
} }

View File

@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using System.Text;
using ZR.Model.System.Generate;
namespace ZR.Model.System.Dto
{
public class GenTableDto
{
public int TableId { get; set; }
public string TableName { get; set; }
public string TableComment { get; set; }
public string SubTableName { get; set; }
public string SubTableFkName { get; set; }
public string ClassName { get; set; }
public string TplCategory { get; set; }
public string BaseNameSpace { get; set; }
public string ModuleName { get; set; }
public string BusinessName { get; set; }
public string FunctionName { get; set; }
public string FunctionAuthor { get; set; }
public string GenType { get; set; }
public string Options { get; set; }
public List<GenTableColumnDto> Columns { get; set; }
}
public class GenTableColumnDto
{
public int ColumnId { get; set; }
public string ColumnName { get; set; }
public int TableId { get; set; }
public string TableName { get; set; }
public string ColumnComment { get; set; }
public string ColumnType { get; set; }
public string CsharpType { get; set; }
public string CsharpField { get; set; }
public bool IsPk { get; set; }
///// <summary>
///// 是否必填1是
///// </summary>
//public bool IsRequired { get; set; }
//public bool IsIncrement { get; set; }
///// <summary>
///// 是否插入
///// </summary>
public bool IsInsert { get; set; }
///// <summary>
///// 是否需要编辑
///// </summary>
public bool IsEdit { get; set; }
///// <summary>
///// isList
///// </summary>
public bool IsList { get; set; }
//public bool IsQuery { get; set; }
///// <summary>
///// 显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)
///// </summary>
public string HtmlType { get; set; }
///// <summary>
///// 查询类型(等于、不等于、大于、小于、范围)
///// </summary>
//public string QueryType { get; set; } = "EQ";
//public int Sort { get; set; }
}
}

View File

@ -8,7 +8,7 @@ namespace ZR.Model.System.Generate
/// 代码生成表 /// 代码生成表
/// </summary> /// </summary>
[SqlSugar.SugarTable("gen_table")] [SqlSugar.SugarTable("gen_table")]
public class GenTable public class GenTable: SysBase
{ {
[SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)] [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int TableId { get; set; } public int TableId { get; set; }
@ -18,7 +18,7 @@ namespace ZR.Model.System.Generate
public string SubTableFkName { get; set; } public string SubTableFkName { get; set; }
public string ClassName { get; set; } public string ClassName { get; set; }
public string TplCategory { get; set; } public string TplCategory { get; set; }
public string PackageName { get; set; } public string BaseNameSpace { get; set; }
public string ModuleName { get; set; } public string ModuleName { get; set; }
public string BusinessName { get; set; } public string BusinessName { get; set; }
public string FunctionName { get; set; } public string FunctionName { get; set; }
@ -26,9 +26,9 @@ namespace ZR.Model.System.Generate
public string GenType { get; set; } public string GenType { get; set; }
public string Options { get; set; } public string Options { get; set; }
[SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)]
public string CreateBy { get; set; } /** 表列信息 */
[SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)] [SqlSugar.SugarColumn(IsIgnore = true)]
public DateTime CreateTime { get; set; } public List<GenTableColumn> Columns { get; set; }
} }
} }

View File

@ -1,4 +1,5 @@
using System; using Newtonsoft.Json;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
@ -8,19 +9,32 @@ namespace ZR.Model.System.Generate
/// 代码生成表字段 /// 代码生成表字段
/// </summary> /// </summary>
[SqlSugar.SugarTable("gen_table_column")] [SqlSugar.SugarTable("gen_table_column")]
public class GenTableColumn public class GenTableColumn: SysBase
{ {
[SqlSugar.SugarColumn(IsIdentity = true, IsPrimaryKey = true)] [SqlSugar.SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
public int ColumnId { get; set; } public int ColumnId { get; set; }
public string ColumnName { get; set; } public string ColumnName { get; set; }
[SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)]
public int TableId { get; set; } public int TableId { get; set; }
[SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)]
public string TableName { get; set; } public string TableName { get; set; }
public string ColumnComment { get; set; } public string ColumnComment { get; set; }
[SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)]
public string ColumnType { get; set; } public string ColumnType { get; set; }
public string CsharpType { get; set; } public string CsharpType { get; set; }
public string CsharpField { get; set; } public string CsharpField { get; set; }
/// <summary>
/// 是否主键1是
/// </summary>
[SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)]
public bool IsPk { get; set; } public bool IsPk { get; set; }
/// <summary>
/// 是否必填1是
/// </summary>
public bool IsRequired { get; set; } public bool IsRequired { get; set; }
[SqlSugar.SugarColumn(IsOnlyIgnoreUpdate = true)]
public bool IsIncrement { get; set; } public bool IsIncrement { get; set; }
/// <summary> /// <summary>
/// 是否插入 /// 是否插入
@ -35,9 +49,14 @@ namespace ZR.Model.System.Generate
/// </summary> /// </summary>
public bool IsList { get; set; } public bool IsList { get; set; }
public bool IsQuery { get; set; } public bool IsQuery { get; set; }
/// <summary>
/// 显示类型(文本框、文本域、下拉框、复选框、单选框、日期控件)
/// </summary>
public string HtmlType { get; set; }
/// <summary>
/// 查询类型(等于、不等于、大于、小于、范围)
/// </summary>
public string QueryType { get; set; } = "EQ";
public int Sort { get; set; } public int Sort { get; set; }
public string CreateBy { get; set; }
public DateTime CreateTime { get; set; }
} }
} }

View File

@ -39,7 +39,6 @@ namespace ZR.Model.System
/// [Computed]计算属性打上此标签对象地insertupdate等操作会忽略此列 /// [Computed]计算属性打上此标签对象地insertupdate等操作会忽略此列
/// </summary> /// </summary>
[SugarColumn(IsIgnore = true)] [SugarColumn(IsIgnore = true)]
//[Computed]
[JsonIgnore] [JsonIgnore]
public DateTime? BeginTime { get; set; } public DateTime? BeginTime { get; set; }
@ -47,7 +46,6 @@ namespace ZR.Model.System
/// 用于搜索使用 /// 用于搜索使用
/// </summary> /// </summary>
[SugarColumn(IsIgnore = true)] [SugarColumn(IsIgnore = true)]
//[Computed]
[JsonIgnore] [JsonIgnore]
public DateTime? EndTime { get; set; } public DateTime? EndTime { get; set; }
} }

View File

@ -5,8 +5,6 @@ using SqlSugar;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.System.Generate; using ZR.Model.System.Generate;
using ZR.Service.System.IService; using ZR.Service.System.IService;
@ -18,14 +16,31 @@ namespace ZR.Service.System
[AppService(ServiceType = typeof(IGenTableService), ServiceLifetime = LifeTime.Transient)] [AppService(ServiceType = typeof(IGenTableService), ServiceLifetime = LifeTime.Transient)]
public class GenTableService : BaseService<GenTable>, IGenTableService public class GenTableService : BaseService<GenTable>, IGenTableService
{ {
public IGenTableColumnService GenTableColumnService;
public GenTableService(IGenTableColumnService genTableColumnService)
{
GenTableColumnService = genTableColumnService;
}
/// <summary> /// <summary>
/// 删除表 /// 删除表
/// </summary> /// </summary>
/// <param name="table"></param> /// <param name="tableIds">需要删除的表id</param>
/// <returns></returns> /// <returns></returns>
public int DeleteGenTable(GenTable table) public int DeleteGenTableByIds(long[] tableIds)
{ {
return Db.Deleteable<GenTable>().Where(f => f.TableName == table.TableName).ExecuteCommand(); Db.Deleteable<GenTable>().Where(f => tableIds.Contains(f.TableId)).ExecuteCommand();
return GenTableColumnService.DeleteGenTableColumn(tableIds);
}
/// <summary>
/// 删除表根据表名
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
public int DeleteGenTableByTbName(string tableName)
{
return Db.Deleteable<GenTable>().Where(f => f.TableName == tableName).ExecuteCommand();
} }
/// <summary> /// <summary>
@ -57,11 +72,15 @@ namespace ZR.Service.System
/// </summary> /// </summary>
/// <param name="table"></param> /// <param name="table"></param>
/// <returns></returns> /// <returns></returns>
public int InsertGenTable(GenTable table) public int ImportGenTable(GenTable table)
{ {
var db = Db; var db = Db;
DeleteGenTable(table); table.Create_time = db.GetDate();
return db.Insertable(table).ExecuteReturnIdentity(); //导入前删除现有表
//DeleteGenTableByIds(new long[] { table.TableId });
DeleteGenTableByTbName(table.TableName);
return db.Insertable(table).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnIdentity();
} }
/// <summary> /// <summary>
@ -73,6 +92,13 @@ namespace ZR.Service.System
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
public int UpdateGenTable(GenTable genTable)
{
var db = Db;
genTable.Update_time = db.GetDate();
return db.Updateable(genTable).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
}
} }
/// <summary> /// <summary>
@ -88,7 +114,26 @@ namespace ZR.Service.System
/// <returns></returns> /// <returns></returns>
public int DeleteGenTableColumn(long tableId) public int DeleteGenTableColumn(long tableId)
{ {
return Db.Deleteable<GenTableColumn>().Where(f => f.TableId == tableId).ExecuteCommand(); return DeleteGenTableColumn(new long[] { tableId });
}
/// <summary>
/// 根据表id批量删除表字段
/// </summary>
/// <param name="tableId"></param>
/// <returns></returns>
public int DeleteGenTableColumn(long[] tableId)
{
return Db.Deleteable<GenTableColumn>().Where(f => tableId.Contains(f.TableId)).ExecuteCommand();
}
/// <summary>
/// 根据表名删除字段
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
public int DeleteGenTableColumnByTableName(string tableName)
{
return Db.Deleteable<GenTableColumn>().Where(f => f.TableName == tableName).ExecuteCommand();
} }
/// <summary> /// <summary>
@ -98,7 +143,7 @@ namespace ZR.Service.System
/// <returns></returns> /// <returns></returns>
public List<GenTableColumn> GenTableColumns(long tableId) public List<GenTableColumn> GenTableColumns(long tableId)
{ {
return GetAll().OrderBy(x => x.Sort).ToList(); return Db.Queryable<GenTableColumn>().Where(f => f.TableId == tableId).OrderBy(x => x.Sort).ToList();
} }
/// <summary> /// <summary>
@ -108,7 +153,17 @@ namespace ZR.Service.System
/// <returns></returns> /// <returns></returns>
public int InsertGenTableColumn(List<GenTableColumn> tableColumn) public int InsertGenTableColumn(List<GenTableColumn> tableColumn)
{ {
return Db.Insertable(tableColumn).ExecuteCommand(); return Db.Insertable(tableColumn).IgnoreColumns(x => new { x.Remark}).ExecuteCommand();
}
/// <summary>
/// 批量更新表字段
/// </summary>
/// <param name="tableColumn"></param>
/// <returns></returns>
public int UpdateGenTableColumn(List<GenTableColumn> tableColumn)
{
return Db.Updateable(tableColumn).IgnoreColumns(x => new { x.Remark }).ExecuteCommand();
} }
} }
} }

View File

@ -12,11 +12,13 @@ namespace ZR.Service.System.IService
{ {
List<GenTable> SelectDbTableListByNamess(string[] tableNames); List<GenTable> SelectDbTableListByNamess(string[] tableNames);
int InsertGenTable(GenTable tables); int ImportGenTable(GenTable tables);
int DeleteGenTable(GenTable table); int DeleteGenTableByIds(long[] tableIds);
int DeleteGenTableByTbName(string tableName);
PagedInfo<GenTable> GetGenTables(GenTable genTable, Model.PagerInfo pagerInfo); PagedInfo<GenTable> GetGenTables(GenTable genTable, Model.PagerInfo pagerInfo);
GenTable GetGenTableInfo(long tableId); GenTable GetGenTableInfo(long tableId);
int UpdateGenTable(GenTable genTable);
} }
public interface IGenTableColumnService public interface IGenTableColumnService
@ -24,7 +26,9 @@ namespace ZR.Service.System.IService
int InsertGenTableColumn(List<GenTableColumn> tableColumn); int InsertGenTableColumn(List<GenTableColumn> tableColumn);
int DeleteGenTableColumn(long tableId); int DeleteGenTableColumn(long tableId);
int DeleteGenTableColumn(long[] tableIds);
int DeleteGenTableColumnByTableName(string tableName);
List<GenTableColumn> GenTableColumns(long tableId); List<GenTableColumn> GenTableColumns(long tableId);
int UpdateGenTableColumn(List<GenTableColumn> tableColumn);
} }
} }

View File

@ -77,6 +77,22 @@ export function importTable(data) {
params: data params: data
}) })
} }
// 删除表数据
export function delTable(tableId) {
return request({
url: '/tool/gen/' + tableId,
method: 'delete'
})
}
// 修改代码生成表信息
export function updateGenTable(data) {
return request({
url: '/tool/gen/',
method: 'put',
data: data
})
}
// /** // /**

View File

@ -182,6 +182,7 @@ export default {
treeParentCode: genTable.treeParentCode, treeParentCode: genTable.treeParentCode,
parentMenuId: genTable.parentMenuId, parentMenuId: genTable.parentMenuId,
}; };
console.log(genTable)
updateGenTable(genTable).then((res) => { updateGenTable(genTable).then((res) => {
this.msgSuccess(res.msg); this.msgSuccess(res.msg);
if (res.code === 200) { if (res.code === 200) {

View File

@ -11,18 +11,18 @@
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
<!--
<el-col :span="12"> <el-col :span="12">
<el-form-item prop="packageName"> <el-form-item prop="baseNameSpace">
<span slot="label"> <span slot="label">
生成包路径 生成命名空间前缀
<el-tooltip content="生成在哪个java包下例如 com.ruoyi.system" placement="top"> <el-tooltip content="比如 ZR.Model目前不支持更换" placement="top">
<i class="el-icon-question"></i> <i class="el-icon-question"></i>
</el-tooltip> </el-tooltip>
</span> </span>
<el-input v-model="info.packageName" /> <el-input v-model="info.baseNameSpace" />
</el-form-item> </el-form-item>
</el-col> </el-col> -->
<el-col :span="12"> <el-col :span="12">
<el-form-item prop="moduleName"> <el-form-item prop="moduleName">
@ -52,7 +52,7 @@
<el-form-item prop="functionName"> <el-form-item prop="functionName">
<span slot="label"> <span slot="label">
生成功能名 生成功能名
<el-tooltip content="用作类描述,例如 用户" placement="top"> <el-tooltip content="用作类描述,例如 用户,代码生成,文章系统" placement="top">
<i class="el-icon-question"></i> <i class="el-icon-question"></i>
</el-tooltip> </el-tooltip>
</span> </span>
@ -60,7 +60,7 @@
</el-form-item> </el-form-item>
</el-col> </el-col>
<el-col :span="12"> <!-- <el-col :span="12">
<el-form-item> <el-form-item>
<span slot="label"> <span slot="label">
上级菜单 上级菜单
@ -68,18 +68,11 @@
<i class="el-icon-question"></i> <i class="el-icon-question"></i>
</el-tooltip> </el-tooltip>
</span> </span>
<treeselect <treeselect :append-to-body="true" v-model="info.parentMenuId" :options="menus" :normalizer="normalizer" :show-count="true" placeholder="请选择系统菜单" />
:append-to-body="true"
v-model="info.parentMenuId"
:options="menus"
:normalizer="normalizer"
:show-count="true"
placeholder="请选择系统菜单"
/>
</el-form-item> </el-form-item>
</el-col> </el-col> -->
<el-col :span="12"> <!-- <el-col :span="12">
<el-form-item prop="genType"> <el-form-item prop="genType">
<span slot="label"> <span slot="label">
生成代码方式 生成代码方式
@ -90,7 +83,7 @@
<el-radio v-model="info.genType" label="0">zip压缩包</el-radio> <el-radio v-model="info.genType" label="0">zip压缩包</el-radio>
<el-radio v-model="info.genType" label="1">自定义路径</el-radio> <el-radio v-model="info.genType" label="1">自定义路径</el-radio>
</el-form-item> </el-form-item>
</el-col> </el-col> -->
<el-col :span="24" v-if="info.genType == '1'"> <el-col :span="24" v-if="info.genType == '1'">
<el-form-item prop="genPath"> <el-form-item prop="genPath">
@ -126,12 +119,7 @@
</el-tooltip> </el-tooltip>
</span> </span>
<el-select v-model="info.treeCode" placeholder="请选择"> <el-select v-model="info.treeCode" placeholder="请选择">
<el-option <el-option v-for="(column, index) in info.columns" :key="index" :label="column.columnName + '' + column.columnComment" :value="column.columnName"></el-option>
v-for="(column, index) in info.columns"
:key="index"
:label="column.columnName + '' + column.columnComment"
:value="column.columnName"
></el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
@ -144,12 +132,7 @@
</el-tooltip> </el-tooltip>
</span> </span>
<el-select v-model="info.treeParentCode" placeholder="请选择"> <el-select v-model="info.treeParentCode" placeholder="请选择">
<el-option <el-option v-for="(column, index) in info.columns" :key="index" :label="column.columnName + '' + column.columnComment" :value="column.columnName"></el-option>
v-for="(column, index) in info.columns"
:key="index"
:label="column.columnName + '' + column.columnComment"
:value="column.columnName"
></el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
@ -162,12 +145,7 @@
</el-tooltip> </el-tooltip>
</span> </span>
<el-select v-model="info.treeName" placeholder="请选择"> <el-select v-model="info.treeName" placeholder="请选择">
<el-option <el-option v-for="(column, index) in info.columns" :key="index" :label="column.columnName + '' + column.columnComment" :value="column.columnName"></el-option>
v-for="(column, index) in info.columns"
:key="index"
:label="column.columnName + '' + column.columnComment"
:value="column.columnName"
></el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
@ -183,12 +161,7 @@
</el-tooltip> </el-tooltip>
</span> </span>
<el-select v-model="info.subTableName" placeholder="请选择" @change="subSelectChange"> <el-select v-model="info.subTableName" placeholder="请选择" @change="subSelectChange">
<el-option <el-option v-for="(table, index) in tables" :key="index" :label="table.tableName + '' + table.tableComment" :value="table.tableName"></el-option>
v-for="(table, index) in tables"
:key="index"
:label="table.tableName + '' + table.tableComment"
:value="table.tableName"
></el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
@ -201,12 +174,7 @@
</el-tooltip> </el-tooltip>
</span> </span>
<el-select v-model="info.subTableFkName" placeholder="请选择"> <el-select v-model="info.subTableFkName" placeholder="请选择">
<el-option <el-option v-for="(column, index) in subColumns" :key="index" :label="column.columnName + '' + column.columnComment" :value="column.columnName"></el-option>
v-for="(column, index) in subColumns"
:key="index"
:label="column.columnName + '' + column.columnComment"
:value="column.columnName"
></el-option>
</el-select> </el-select>
</el-form-item> </el-form-item>
</el-col> </el-col>
@ -223,15 +191,15 @@ export default {
props: { props: {
info: { info: {
type: Object, type: Object,
default: null default: null,
}, },
tables: { tables: {
type: Array, type: Array,
default: null default: null,
}, },
menus: { menus: {
type: Array, type: Array,
default: [] default: [],
}, },
}, },
data() { data() {
@ -239,28 +207,28 @@ export default {
subColumns: [], subColumns: [],
rules: { rules: {
tplCategory: [ tplCategory: [
{ required: true, message: "请选择生成模板", trigger: "blur" } { required: true, message: "请选择生成模板", trigger: "blur" },
], ],
packageName: [ packageName: [
{ required: true, message: "请输入生成包路径", trigger: "blur" } { required: true, message: "请输入生成包路径", trigger: "blur" },
], ],
moduleName: [ moduleName: [
{ required: true, message: "请输入生成模块名", trigger: "blur" } { required: true, message: "请输入生成模块名", trigger: "blur" },
], ],
businessName: [ businessName: [
{ required: true, message: "请输入生成业务名", trigger: "blur" } { required: true, message: "请输入生成业务名", trigger: "blur" },
], ],
functionName: [ functionName: [
{ required: true, message: "请输入生成功能名", trigger: "blur" } { required: true, message: "请输入生成功能名", trigger: "blur" },
], ],
} },
}; };
}, },
created() {}, created() {},
watch: { watch: {
'info.subTableName': function(val) { "info.subTableName": function (val) {
this.setSubTableColumns(val); this.setSubTableColumns(val);
} },
}, },
methods: { methods: {
/** 转换菜单数据结构 */ /** 转换菜单数据结构 */
@ -271,18 +239,18 @@ export default {
return { return {
id: node.menuId, id: node.menuId,
label: node.menuName, label: node.menuName,
children: node.children children: node.children,
}; };
}, },
/** 选择子表名触发 */ /** 选择子表名触发 */
subSelectChange(value) { subSelectChange(value) {
this.info.subTableFkName = ''; this.info.subTableFkName = "";
}, },
/** 选择生成模板触发 */ /** 选择生成模板触发 */
tplSelectChange(value) { tplSelectChange(value) {
if(value !== 'sub') { if (value !== "sub") {
this.info.subTableName = ''; this.info.subTableName = "";
this.info.subTableFkName = ''; this.info.subTableFkName = "";
} }
}, },
/** 设置关联外键 */ /** 设置关联外键 */
@ -294,7 +262,7 @@ export default {
break; break;
} }
} }
} },
} },
}; };
</script> </script>

View File

@ -14,12 +14,12 @@
<el-tooltip class="item" effect="dark" content="系统会根据项目命名空间自动生成IService、Service、Models等子命名空间" placement="bottom"> <el-tooltip class="item" effect="dark" content="系统会根据项目命名空间自动生成IService、Service、Models等子命名空间" placement="bottom">
<el-input v-model="queryParams.baseSpace" clearable placeholder="如Zr" /> <el-input v-model="queryParams.baseSpace" clearable placeholder="如Zr" />
</el-tooltip> </el-tooltip>
</el-form-item> --> </el-form-item>
<el-form-item label="去掉表名前缀:"> <el-form-item label="去掉表名前缀:">
<el-tooltip class="item" effect="dark" content="表名直接变为类名,去掉表名前缀。" placement="bottom"> <el-tooltip class="item" effect="dark" content="表名直接变为类名,去掉表名前缀。" placement="bottom">
<el-input v-model="queryParams.replaceTableNameStr" clearable width="300" placeholder="例如sys_" /> <el-input v-model="queryParams.replaceTableNameStr" clearable width="300" placeholder="例如sys_" />
</el-tooltip> </el-tooltip>
</el-form-item> </el-form-item> -->
<el-form-item> <el-form-item>
<el-button type="primary" @click="handleSearch()">查询</el-button> <el-button type="primary" @click="handleSearch()">查询</el-button>
<el-button type="default" icon="el-icon-refresh" size="small" @click="loadTableData()">刷新</el-button> <el-button type="default" icon="el-icon-refresh" size="small" @click="loadTableData()">刷新</el-button>
@ -32,10 +32,10 @@
</el-col> </el-col>
<el-col :span="1.5"> <el-col :span="1.5">
<el-button type="danger" plain icon="el-icon-delete" size="mini" v-hasPermi="['tool:gen:delete']">删除</el-button> <el-button type="danger" :disabled="multiple" plain icon="el-icon-delete" @click="handleDelete" size="mini" v-hasPermi="['tool:gen:delete']">删除</el-button>
</el-col> </el-col>
</el-row> </el-row>
<el-table ref="gridtable" v-loading="tableloading" :data="tableData" border stripe highlight-current-row height="500px" style="width: 100%;"> <el-table ref="gridtable" v-loading="tableloading" :data="tableData" border @selection-change="handleSelectionChange" highlight-current-row height="500px">
<el-table-column type="selection" align="center" width="55"></el-table-column> <el-table-column type="selection" align="center" width="55"></el-table-column>
<el-table-column label="序号" type="index" width="50" align="center"> <el-table-column label="序号" type="index" width="50" align="center">
<template slot-scope="scope"> <template slot-scope="scope">
@ -51,6 +51,11 @@
<template slot-scope="scope"> <template slot-scope="scope">
<el-button type="text" icon="el-icon-view" @click="handlePreview()">预览</el-button> <el-button type="text" icon="el-icon-view" @click="handlePreview()">预览</el-button>
<el-button type="text" icon="el-icon-edit" @click="handleEditTable(scope.row)">编辑</el-button> <el-button type="text" icon="el-icon-edit" @click="handleEditTable(scope.row)">编辑</el-button>
<el-popconfirm title="确定删除吗?" @onConfirm="handleDelete(scope.row)" style="margin-left:10px">
<el-button slot="reference" v-hasPermi="['tool:gen:delete']" size="mini" type="text" icon="el-icon-delete">删除</el-button>
</el-popconfirm>
<el-button type="text" icon="el-icon-download" @click="handleShowDialog(scope.row)" v-hasPermi="['tool:gen:code']">生成代码</el-button> <el-button type="text" icon="el-icon-download" @click="handleShowDialog(scope.row)" v-hasPermi="['tool:gen:code']">生成代码</el-button>
</template> </template>
</el-table-column> </el-table-column>
@ -87,7 +92,7 @@
</template> </template>
<script> <script>
import { codeGenerator, getGenTable } from "@/api/tool/gen"; import { codeGenerator, getGenTable, delTable } from "@/api/tool/gen";
import importTable from "./importTable"; import importTable from "./importTable";
import { Loading } from "element-ui"; import { Loading } from "element-ui";
@ -128,6 +133,10 @@ export default {
checkedQueryColumn: [], checkedQueryColumn: [],
// //
coverd: true, coverd: true,
//
tableIds: [],
//
multiple: true
}; };
}, },
created() { created() {
@ -159,7 +168,6 @@ export default {
handleShowDialog(row) { handleShowDialog(row) {
this.showGenerate = true; this.showGenerate = true;
this.currentSelected = row; this.currentSelected = row;
}, },
/** /**
* 点击生成服务端代码 * 点击生成服务端代码
@ -181,7 +189,8 @@ export default {
const pageLoading = Loading.service(loadop); const pageLoading = Loading.service(loadop);
var seachdata = { var seachdata = {
dbName: this.codeform.dbName, // dbName: this.codeform.dbName,
tableId: this.currentSelected.tableId,
tableName: this.currentSelected.name, tableName: this.currentSelected.name,
baseSpace: this.codeform.baseSpace, baseSpace: this.codeform.baseSpace,
replaceTableNameStr: this.codeform.replaceTableNameStr, replaceTableNameStr: this.codeform.replaceTableNameStr,
@ -236,6 +245,21 @@ export default {
openImportTable() { openImportTable() {
this.$refs.import.show(); this.$refs.import.show();
}, },
handleDelete(row) {
const tableIds = row.tableId || this.tableIds;
delTable(tableIds.toString()).then(res => {
if (res.code == 200) {
this.msgSuccess('删除成功')
this.handleSearch();
}
})
},
handleSelectionChange(section) {
this.tableIds = section.map((item) => item.tableId);
this.multiple = !section.length;
console.log(this.tableIds)
},
}, },
}; };
</script> </script>

View File

@ -27,47 +27,6 @@
<param name="data"></param> <param name="data"></param>
<returns></returns> <returns></returns>
</member> </member>
<member name="T:ZR.Admin.WebApi.Controllers.GiftController">
<summary>
代码自动生成
</summary>
</member>
<member name="F:ZR.Admin.WebApi.Controllers.GiftController._GiftService">
<summary>
接口
</summary>
</member>
<member name="M:ZR.Admin.WebApi.Controllers.GiftController.QueryGift(ZR.Model.Dto.GiftQueryDto)">
<summary>
查询列表
</summary>
<returns></returns>
</member>
<member name="M:ZR.Admin.WebApi.Controllers.GiftController.GetGift(System.Int32)">
<summary>
查询详情
</summary>
<param name="GiftId"></param>
<returns></returns>
</member>
<member name="M:ZR.Admin.WebApi.Controllers.GiftController.AddGift(ZR.Model.Dto.GiftDto)">
<summary>
添加
</summary>
<returns></returns>
</member>
<member name="M:ZR.Admin.WebApi.Controllers.GiftController.UpdateGift(ZR.Model.Dto.GiftDto)">
<summary>
更新
</summary>
<returns></returns>
</member>
<member name="M:ZR.Admin.WebApi.Controllers.GiftController.DeleteGift(System.Int32)">
<summary>
删除
</summary>
<returns></returns>
</member>
<member name="T:ZR.Admin.WebApi.Controllers.CodeGeneratorController"> <member name="T:ZR.Admin.WebApi.Controllers.CodeGeneratorController">
<summary> <summary>
代码生成 代码生成
@ -112,7 +71,7 @@
</member> </member>
<member name="M:ZR.Admin.WebApi.Controllers.CodeGeneratorController.Remove(System.String)"> <member name="M:ZR.Admin.WebApi.Controllers.CodeGeneratorController.Remove(System.String)">
<summary> <summary>
代码生成删除 删除代码生成
</summary> </summary>
<param name="tableIds"></param> <param name="tableIds"></param>
<returns></returns> <returns></returns>
@ -125,6 +84,12 @@
<param name="dbName"></param> <param name="dbName"></param>
<returns></returns> <returns></returns>
</member> </member>
<member name="M:ZR.Admin.WebApi.Controllers.CodeGeneratorController.EditSave(ZR.Model.System.Dto.GenTableDto)">
<summary>
代码生成保存
</summary>
<returns></returns>
</member>
<member name="M:ZR.Admin.WebApi.Controllers.HomeController.Health"> <member name="M:ZR.Admin.WebApi.Controllers.HomeController.Health">
<summary> <summary>
心跳 心跳

Binary file not shown.