优化代码生成模板

This commit is contained in:
izory 2021-09-13 18:38:54 +08:00
parent baec8f0a91
commit e3d9b8103b
11 changed files with 355 additions and 247 deletions

View File

@ -15,7 +15,7 @@ namespace {DtosNamespace}.Dto
public class {ModelTypeName}QueryDto: PagerInfo public class {ModelTypeName}QueryDto: PagerInfo
{ {
public DateTime? BeginTime { get; set; }
public DateTime? EndTime { get; set; }
} }
} }

View File

@ -1,38 +1,31 @@
<template> <template>
<div class="app-container"> <div class="app-container">
<el-row :gutter="24">
<!-- :model属性用于表单验证使用 比如下面的el-form-item 的 prop属性用于对表单值进行验证操作 --> <!-- :model属性用于表单验证使用 比如下面的el-form-item 的 prop属性用于对表单值进行验证操作 -->
<el-form :model="queryParams" label-position="left" inline ref="queryForm" :label-width="labelWidth" v-show="showSearch" @submit.native.prevent> <el-form :model="queryParams" label-position="left" inline ref="queryForm" :label-width="labelWidth" v-show="showSearch" @submit.native.prevent>
<el-col :span="6"> <el-form-item label="文本文字">
<el-form-item label="文本文字"> <el-input v-model="queryParams.xxx" placeholder="" />
<el-input v-model="queryParams.xxx" placeholder="" /> </el-form-item>
</el-form-item> <el-form-item label="数字">
</el-col> <el-input v-model.number="queryParams.xxx" placeholder="" />
<el-col :span="6"> </el-form-item>
<el-form-item label="数字">
<el-input v-model.number="queryParams.xxx" placeholder="" /> <el-form-item label="下拉框">
</el-form-item> <el-select v-model="queryParams.xxx" placeholder="">
</el-col> <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
<el-col :span="6"> </el-select>
<el-form-item label="下拉框"> </el-form-item>
<el-select v-model="queryParams.xxx" placeholder="">
<el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" /> <el-form-item label="时间范围">
</el-select> <el-date-picker size="small" style="width: 240px" v-model="timeRange" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
</el-form-item> </el-date-picker>
</el-col> </el-form-item>
<el-col :span="6">
<el-form-item label="时间范围">
<el-date-picker size="small" style="width: 240px" v-model="timeRange" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期">
</el-date-picker>
</el-form-item>
</el-col>
<el-col :span="24" style="text-align:center;">
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-col>
</el-form>
</el-row>
<el-row class="mb8" style="text-align:center">
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-row>
</el-form>
<!-- 工具区域 --> <!-- 工具区域 -->
<el-row :gutter="10" class="mb8"> <el-row :gutter="10" class="mb8">
<el-col :span="1.5"> <el-col :span="1.5">
@ -60,16 +53,16 @@
</template> </template>
</el-table-column> </el-table-column>
</el-table> </el-table>
<pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" /> <el-pagination class="mt10" background :total="total" :current-page.sync="queryParams.pageNum" :page-size="queryParams.pageSize" :page-sizes="[20, 30, 50, 100]" @size-change="handleSizeChange" @current-change="getList" />
<!-- 添加或修改菜单对话框 --> <!-- 添加或修改菜单对话框 -->
<el-dialog :title="title" :visible.sync="open" append-to-body> <el-dialog :title="title" :lock-scroll="false" :visible.sync="open" >
<el-form ref="form" :model="form" :rules="rules" label-width="100px"> <el-form ref="form" :model="form" :rules="rules" :label-width="formLabelWidth">
{VueViewFormContent} {VueViewFormContent}
</el-form> </el-form>
<div slot="footer" class="dialog-footer" v-if="btnSubmitVisible"> <div slot="footer" class="dialog-footer" v-if="btnSubmitVisible">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button> <el-button @click="cancel">取 消</el-button>
<el-button type="primary" @click="submitForm">确 定</el-button>
</div> </div>
</el-dialog> </el-dialog>
@ -89,6 +82,7 @@ export default {
data() { data() {
return { return {
labelWidth: "100px", labelWidth: "100px",
formLabelWidth:"100px",
// 选中数组 // 选中数组
ids: [], ids: [],
// 非单个禁用 // 非单个禁用
@ -161,6 +155,7 @@ export default {
this.resetForm("queryForm"); this.resetForm("queryForm");
this.queryParams = { this.queryParams = {
pageNum: 1, pageNum: 1,
pageSize: 20,
//TODO 重置字段 //TODO 重置字段
}; };
}, },
@ -170,6 +165,12 @@ export default {
this.single = selection.length!=1 this.single = selection.length!=1
this.multiple = !selection.length; this.multiple = !selection.length;
}, },
/** 选择每页显示数量*/
handleSizeChange(val) {
this.queryParams.pageSize = val;
this.queryParams.pageNum = 1;
this.handleQuery();
},
/** 搜索按钮操作 */ /** 搜索按钮操作 */
handleQuery() { handleQuery() {
this.getList(); this.getList();
@ -179,8 +180,6 @@ export default {
this.reset(); this.reset();
this.open = true; this.open = true;
this.title = "添加"; this.title = "添加";
//TODO 业务代码
}, },
/** 删除按钮操作 */ /** 删除按钮操作 */
handleDelete(row) { handleDelete(row) {
@ -201,6 +200,9 @@ export default {
} }
}); });
}, },
beforeFileUpload(file) { },
//文件上传成功方法
{vueJsMethod}
/** 提交按钮 */ /** 提交按钮 */
submitForm: function () { submitForm: function () {
this.$refs["form"].validate((valid) => { this.$refs["form"].validate((valid) => {
@ -230,4 +232,14 @@ export default {
.table-td-thumb { .table-td-thumb {
width: 80px; width: 80px;
} }
.icon {
width: 100px;
}
.uploader-icon {
width: 50px;
height: 50px;
line-height: 50px;
border: 1px dashed #ccc;
margin-bottom: 10px;
}
</style> </style>

View File

@ -0,0 +1,152 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.CodeGenerator.CodeGenerator;
namespace ZR.CodeGenerator
{
public class CodeGenerateTemplate
{
#region Template
public static string GetVueJsMethod(DbColumnInfo dbColumnInfo)
{
string columnName = CodeGeneratorTool.FirstLowerCase(dbColumnInfo.DbColumnName);
string js = "";
if (CodeGeneratorTool.imageFiled.Any(f => columnName.Contains(f)))
{
js += $"handleUpload{columnName}Success(res, file) {{\n";
js += $" this.form.{columnName} = URL.createObjectURL(file.raw);\n";
js += " // this.$refs.upload.clearFiles();\n";
js += "},\n";
}
return js;
}
//rules
public static string GetFormRules(DbColumnInfo dbFieldInfo)
{
string vueViewEditFromRuleContent = "";
//Rule 规则验证
if (!dbFieldInfo.IsNullable && !dbFieldInfo.IsIdentity)
{
vueViewEditFromRuleContent += $" {dbFieldInfo.DbColumnName}: [\n";
vueViewEditFromRuleContent += $" {{ required: true, message:\"{dbFieldInfo.ColumnDescription}\", trigger: \"blur\"}},\n";
//vueViewEditFromRuleContent += " { min: 2, max: 50, message: \"长度在 2 到 50 个字符\", trigger:\"blur\" }\n";
vueViewEditFromRuleContent += " ],\n";
}
return vueViewEditFromRuleContent;
}
//model 属性
public static string GetModelTemplate(DbColumnInfo dbFieldInfo)
{
string columnName = dbFieldInfo.DbColumnName.Substring(0, 1).ToUpper() + dbFieldInfo.DbColumnName[1..];
var modelcontent = "";
modelcontent += " /// <summary>\n";
modelcontent += $" /// 描述 :{dbFieldInfo.ColumnDescription}\n";
modelcontent += $" /// 空值 :{dbFieldInfo.IsNullable}\n";
modelcontent += $" /// 默认 :{dbFieldInfo.DefaultValue}\n";
modelcontent += " /// </summary>\n";
if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey)
{
modelcontent += $" [SqlSugar.SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPrimarykey.ToString().ToLower()}, IsIdentity = {dbFieldInfo.IsIdentity.ToString().ToLower()})]\n";
}
modelcontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r";
return modelcontent;
}
//DTO model
public static string GetDtoContent(DbColumnInfo dbFieldInfo)
{
string columnName = dbFieldInfo.DbColumnName.Substring(0, 1).ToUpper() + dbFieldInfo.DbColumnName[1..];
string InputDtoContent = "";
InputDtoContent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r";
return InputDtoContent;
}
//form-item
public static string GetVueViewFormContent(DbColumnInfo dbFieldInfo)
{
string columnName = CodeGeneratorTool.FirstLowerCase(dbFieldInfo.DbColumnName);
string labelName = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName);
string vueViewFromContent = "";
string labelDisabled = dbFieldInfo.IsIdentity ? ":disabled=\"true\"" : "";
string placeHolder = dbFieldInfo.IsIdentity ? "" : $"请输入{CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName)}";
if (dbFieldInfo.DataType == "datetime")
{
//时间
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-form-item>\n";
}
else if (CodeGeneratorTool.imageFiled.Any(f => columnName.Contains(f)))
{
//图片
vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">\n";
vueViewFromContent += $" <el-upload class=\"avatar-uploader\" name=\"file\" action=\"/api/upload/saveFile/\" :show-file-list=\"false\" :on-success=\"handleUpload{columnName}Success\" :before-upload=\"beforeFileUpload\">\n";
vueViewFromContent += $" <img v-if=\"form.{columnName}\" :src=\"form.{columnName}\" class=\"icon\">\n";
vueViewFromContent += " <i v-else class=\"el-icon-plus uploader-icon\"></i>\n";
vueViewFromContent += " </el-upload>\n";
vueViewFromContent += $" <el-input v-model=\"form.{columnName}\" placeholder=\"请上传文件或手动输入文件地址\"></el-input>\n";
vueViewFromContent += " </el-form-item>\n";
}
else if (CodeGeneratorTool.radioFiled.Any(f => columnName.Contains(f)) && (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint" || dbFieldInfo.DataType == "int"))
{
vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">";
vueViewFromContent += $" <el-radio-group v-model=\"form.{columnName}\">\n";
vueViewFromContent += " <el-radio v-for=\"dict in statusOptions\" :key=\"dict.dictValue\" :label=\"dict.dictValue\">{{dict.dictLabel}}</el-radio>\n";
vueViewFromContent += " </el-radio-group>\n";
vueViewFromContent += " </el-form-item>\n";
}
else
{
vueViewFromContent += $" <el-form-item label=\"{ CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" :label-width=\"labelWidth\" prop=\"{CodeGeneratorTool.FirstLowerCase(columnName)}\">\n";
vueViewFromContent += $" <el-input v-model=\"form.{CodeGeneratorTool.FirstLowerCase(columnName)}\" placeholder=\"{placeHolder}\" {labelDisabled}/>\n";
vueViewFromContent += " </el-form-item>\n";
}
return vueViewFromContent;
}
//table-column
public static string GetTableColumn(DbColumnInfo dbFieldInfo)
{
string columnName = CodeGeneratorTool.FirstLowerCase(dbFieldInfo.DbColumnName);
string label = CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName);
string vueViewListContent = "";
string showToolTip = dbFieldInfo.DataType.Contains("varchar") ? ":show-overflow-tooltip=\"true\"" : "";
if (CodeGeneratorTool.imageFiled.Any(f => columnName.ToLower().Contains(f)))
{
vueViewListContent += $" <el-table-column prop=\"{ columnName}\" label=\"图片\">\n";
vueViewListContent += " <template slot-scope=\"scope\">\n";
vueViewListContent += $" <el-image class=\"table-td-thumb\" :src=\"scope.row.{columnName}\" :preview-src-list=\"[scope.row.{columnName}]\"></el-image>\n";
vueViewListContent += " </template>\n";
vueViewListContent += " </el-table-column>\n";
}
else if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint")
{
vueViewListContent += $" <el-table-column prop=\"{columnName}\" label=\"{label}\" width=\"120\" >\n";
vueViewListContent += " <template slot-scope=\"scope\">\n";
vueViewListContent += $" <el-tag :type=\"scope.row.{columnName} === true ? 'success' : 'info'\" disable-transitions >";
vueViewListContent += $" {{scope.row.{columnName}===true?'启用':'禁用'}} </el-tag>\n";
vueViewListContent += " </template>\n";
vueViewListContent += " </el-table-column>\n";
}
else
{
//table-column
vueViewListContent += $" <el-table-column prop=\"{CodeGeneratorTool.FirstLowerCase(columnName)}\" label=\"{CodeGeneratorTool.GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" align=\"center\" width=\"100\" {showToolTip} />\n";
}
return vueViewListContent;
}
#endregion
}
}

View File

@ -1,10 +1,8 @@
using SqlSugar; using SqlSugar;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using ZR.CodeGenerator.CodeGenerator;
using ZR.CodeGenerator.Model; using ZR.CodeGenerator.Model;
using ZR.CodeGenerator.Service; using ZR.CodeGenerator.Service;
@ -25,10 +23,10 @@ namespace ZR.CodeGenerator
/// <summary> /// <summary>
/// InputDto输入实体是不包含字段 /// InputDto输入实体是不包含字段
/// </summary> /// </summary>
private static string[] inputDtoNoField = new string[] { "DeleteMark", "CreateTime", "updateTime", "addtime" }; public static readonly string[] inputDtoNoField = new string[] { "DeleteMark", "CreateTime", "updateTime", "addtime" };
private static string[] imageFiled = new string[] { "icon", "img", "image", "url", "pic" }; public static readonly string[] imageFiled = new string[] { "icon", "img", "image", "url", "pic", "photo" };
private static string[] selectFiled = new string[] { "status", "type", "state" }; public static readonly string[] selectFiled = new string[] { "status", "type", "state", "sex", "gender" };
private static string[] radioFiled = new string[] { "status", "state", "is" }; public static readonly string[] radioFiled = new string[] { "status", "state", "isShow", "isHidden", "ishide" };
/// <summary> /// <summary>
/// 代码生成器入口方法 /// 代码生成器入口方法
@ -38,6 +36,8 @@ namespace ZR.CodeGenerator
public static void Generate(DbTableInfo dbTableInfo, GenerateDto dto) public static void Generate(DbTableInfo dbTableInfo, GenerateDto dto)
{ {
//_option.BaseNamespace = baseNamespace; //_option.BaseNamespace = baseNamespace;
//_option.TableList = listTable;
_option.ReplaceTableNameStr = dto.replaceTableNameStr;
_option.DtosNamespace = "ZR.Model"; _option.DtosNamespace = "ZR.Model";
_option.ModelsNamespace = "ZR.Model"; _option.ModelsNamespace = "ZR.Model";
_option.RepositoriesNamespace = "ZR.Repository"; _option.RepositoriesNamespace = "ZR.Repository";
@ -45,8 +45,6 @@ namespace ZR.CodeGenerator
_option.IServicsNamespace = "ZR.Service"; _option.IServicsNamespace = "ZR.Service";
_option.ServicesNamespace = "ZR.Service"; _option.ServicesNamespace = "ZR.Service";
_option.ApiControllerNamespace = "ZR.Admin.WebApi"; _option.ApiControllerNamespace = "ZR.Admin.WebApi";
_option.ReplaceTableNameStr = dto.replaceTableNameStr;
//_option.TableList = listTable;
CodeGeneraterService codeGeneraterService = new CodeGeneraterService(); CodeGeneraterService codeGeneraterService = new CodeGeneraterService();
@ -72,7 +70,7 @@ namespace ZR.CodeGenerator
string keyTypeName = "int";//主键数据类型 string keyTypeName = "int";//主键数据类型
string modelContent = "";//数据库模型字段 string modelContent = "";//数据库模型字段
string InputDtoContent = "";//输入模型 string InputDtoContent = "";//输入模型
string outputDtoContent = "";//输出模型 //string outputDtoContent = "";//输出模型
string updateColumn = "";//修改数据映射字段 string updateColumn = "";//修改数据映射字段
string vueViewListContent = string.Empty;//Vue列表输出内容 string vueViewListContent = string.Empty;//Vue列表输出内容
string vueViewFormContent = string.Empty;//Vue表单输出内容 string vueViewFormContent = string.Empty;//Vue表单输出内容
@ -80,6 +78,7 @@ namespace ZR.CodeGenerator
string vueViewEditFromBindContent = string.Empty;//Vue显示初始化输出内容 string vueViewEditFromBindContent = string.Empty;//Vue显示初始化输出内容
string vueViewSaveBindContent = string.Empty;//Vue保存时输出内容 string vueViewSaveBindContent = string.Empty;//Vue保存时输出内容
string vueViewEditFromRuleContent = string.Empty;//Vue数据校验 string vueViewEditFromRuleContent = string.Empty;//Vue数据校验
string vueJsMethod = string.Empty;//Vue js自定义方法
foreach (DbColumnInfo dbFieldInfo in listField) foreach (DbColumnInfo dbFieldInfo in listField)
{ {
@ -109,11 +108,12 @@ namespace ZR.CodeGenerator
} }
dbFieldInfo.DbColumnName = columnName; dbFieldInfo.DbColumnName = columnName;
modelContent += GetModelTemplate(dbFieldInfo); modelContent += CodeGenerateTemplate.GetModelTemplate(dbFieldInfo);
vueViewFormContent += GetVueViewFormContent(dbFieldInfo); vueViewFormContent += CodeGenerateTemplate.GetVueViewFormContent(dbFieldInfo);
vueViewListContent += GetTableColumn(dbFieldInfo); vueJsMethod += CodeGenerateTemplate.GetVueJsMethod(dbFieldInfo);
vueViewEditFromRuleContent += GetFormRules(dbFieldInfo); vueViewListContent += CodeGenerateTemplate.GetTableColumn(dbFieldInfo);
InputDtoContent += GetDtoContent(dbFieldInfo); vueViewEditFromRuleContent += CodeGenerateTemplate.GetFormRules(dbFieldInfo);
InputDtoContent += CodeGenerateTemplate.GetDtoContent(dbFieldInfo);
} }
if (dto.genFiles.Contains(1)) if (dto.genFiles.Contains(1))
{ {
@ -138,127 +138,12 @@ namespace ZR.CodeGenerator
} }
if (dto.genFiles.Contains(6)) if (dto.genFiles.Contains(6))
{ {
GenerateVueViews(modelTypeName, primaryKey, modelTypeDesc, vueViewListContent, vueViewFormContent, vueViewEditFromContent, vueViewEditFromBindContent, vueViewSaveBindContent, vueViewEditFromRuleContent, ifExsitedCovered); GenerateVueViews(modelTypeName, primaryKey, modelTypeDesc, vueViewListContent, vueViewFormContent, vueViewEditFromContent, vueViewEditFromBindContent, vueViewSaveBindContent, vueViewEditFromRuleContent, vueJsMethod, ifExsitedCovered);
} }
//GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); //GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateOutputDto(modelTypeName, modelTypeDesc, outputDtocontent, ifExsitedCovered); //GenerateOutputDto(modelTypeName, modelTypeDesc, outputDtocontent, ifExsitedCovered);
} }
#region Template
//rules
private static string GetFormRules(DbColumnInfo dbFieldInfo)
{
string vueViewEditFromRuleContent = "";
//Rule 规则验证
if (!dbFieldInfo.IsNullable && !dbFieldInfo.IsIdentity)
{
vueViewEditFromRuleContent += $" {dbFieldInfo.DbColumnName}: [\n";
vueViewEditFromRuleContent += $" {{ required: true, message:\"{dbFieldInfo.ColumnDescription}\", trigger: \"blur\"}},\n";
//vueViewEditFromRuleContent += " { min: 2, max: 50, message: \"长度在 2 到 50 个字符\", trigger:\"blur\" }\n";
vueViewEditFromRuleContent += " ],\n";
}
return vueViewEditFromRuleContent;
}
//model 属性
private static string GetModelTemplate(DbColumnInfo dbFieldInfo)
{
string columnName = dbFieldInfo.DbColumnName.Substring(0, 1).ToUpper() + dbFieldInfo.DbColumnName[1..];
var modelcontent = "";
modelcontent += " /// <summary>\n";
modelcontent += $" /// 描述 :{dbFieldInfo.ColumnDescription}\n";
modelcontent += $" /// 空值 :{dbFieldInfo.IsNullable}\n";
modelcontent += $" /// 默认 :{dbFieldInfo.DefaultValue}\n";
modelcontent += " /// </summary>\n";
if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey)
{
modelcontent += $" [SqlSugar.SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPrimarykey.ToString().ToLower()}, IsIdentity = {dbFieldInfo.IsIdentity.ToString().ToLower()})]\n";
}
modelcontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r";
return modelcontent;
}
//DTO model
private static string GetDtoContent(DbColumnInfo dbFieldInfo)
{
string columnName = dbFieldInfo.DbColumnName.Substring(0, 1).ToUpper() + dbFieldInfo.DbColumnName[1..];
string InputDtoContent = "";
InputDtoContent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r";
return InputDtoContent;
}
//form-item
private static string GetVueViewFormContent(DbColumnInfo dbFieldInfo)
{
string columnName = FirstLowerCase(dbFieldInfo.DbColumnName);
string labelName = GetLabelName(dbFieldInfo.ColumnDescription, columnName);
string vueViewFromContent = "";
string labelDisabled = dbFieldInfo.IsIdentity ? ":disabled=\"true\"" : "";
if (dbFieldInfo.DataType == "datetime")
{
vueViewFromContent += "";
}
else if (((IList)imageFiled).Contains(columnName))
{
//TODO 图片
}
else if (radioFiled.Any(f => columnName.Contains(f)) && (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint" || dbFieldInfo.DataType == "int"))
{
vueViewFromContent += $" <el-col :span=\"12\">\n";
vueViewFromContent += $" <el-form-item label=\"{labelName}\" :label-width=\"labelWidth\" prop=\"{columnName}\">";
vueViewFromContent += $" <el-radio-group v-model=\"form.{columnName}\">\n";
vueViewFromContent += " <el-radio v-for=\"dict in statusOptions\" :key=\"dict.dictValue\" :label=\"dict.dictValue\">{{dict.dictLabel}}</el-radio>\n";
vueViewFromContent += " </el-radio-group>\n";
vueViewFromContent += " </el-form-item>\n";
vueViewFromContent += " </el-col>\n";
}
else
{
vueViewFromContent += $" <el-col :span=\"12\">\n";
vueViewFromContent += $" <el-form-item label=\"{ GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" :label-width=\"labelWidth\" prop=\"{FirstLowerCase(columnName)}\">\n";
vueViewFromContent += $" <el-input v-model=\"form.{FirstLowerCase(columnName)}\" placeholder=\"请输入{GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" {labelDisabled}/>\n";
vueViewFromContent += " </el-form-item>\n";
vueViewFromContent += " </el-col>\n";
}
return vueViewFromContent;
}
//table-column
private static string GetTableColumn(DbColumnInfo dbFieldInfo)
{
string columnName = FirstLowerCase(dbFieldInfo.DbColumnName);
string label = GetLabelName(dbFieldInfo.ColumnDescription, columnName);
string vueViewListContent = "";
string showToolTip = dbFieldInfo.DataType.Contains("varchar") ? ":show-overflow-tooltip=\"true\"" : "";
if (imageFiled.Any(f => columnName.ToLower().Contains(f)))
{
vueViewListContent += $" <el-table-column prop=\"{ columnName}\" label=\"图片\">\n";
vueViewListContent += " <template slot-scope=\"scope\">\n";
vueViewListContent += $" <el-image class=\"table-td-thumb\" :src=\"scope.row.{columnName}\" :preview-src-list=\"[scope.row.{columnName}]\"></el-image>\n";
vueViewListContent += " </template>\n";
vueViewListContent += " </el-table-column>\n";
}
else if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint")
{
vueViewListContent += $" <el-table-column prop=\"{columnName}\" label=\"{label}\" width=\"120\" >\n";
vueViewListContent += " <template slot-scope=\"scope\">\n";
vueViewListContent += $" <el-tag :type=\"scope.row.{columnName} === true ? 'success' : 'info'\" disable-transitions >";
vueViewListContent += $" {{scope.row.{columnName}===true?'启用':'禁用'}} </el-tag>\n";
vueViewListContent += " </template>\n";
vueViewListContent += " </el-table-column>\n";
}
else
{
//table-column
vueViewListContent += $" <el-table-column prop=\"{FirstLowerCase(columnName)}\" label=\"{GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" align=\"center\" width=\"100\" {showToolTip} />\n";
}
return vueViewListContent;
}
#endregion
#region Model #region Model
@ -320,7 +205,7 @@ namespace ZR.CodeGenerator
var fullPath = servicesPath + modelTypeName + "Dto.cs"; var fullPath = servicesPath + modelTypeName + "Dto.cs";
Console.WriteLine(fullPath); Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !ifExsitedCovered) if (File.Exists(fullPath) && !ifExsitedCovered)
return Tuple.Create(fullPath, ""); ; return Tuple.Create(fullPath, ""); ;
var content = ReadTemplate("InputDtoTemplate.txt"); var content = ReadTemplate("InputDtoTemplate.txt");
content = content content = content
.Replace("{DtosNamespace}", _option.DtosNamespace) .Replace("{DtosNamespace}", _option.DtosNamespace)
@ -390,7 +275,7 @@ namespace ZR.CodeGenerator
var fullPath = $"{iServicesPath}\\I{modelTypeName}Service.cs"; var fullPath = $"{iServicesPath}\\I{modelTypeName}Service.cs";
Console.WriteLine(fullPath); Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !ifExsitedCovered) if (File.Exists(fullPath) && !ifExsitedCovered)
return Tuple.Create(fullPath, ""); return Tuple.Create(fullPath, "");
var content = ReadTemplate("IServiceTemplate.txt"); var content = ReadTemplate("IServiceTemplate.txt");
content = content.Replace("{ModelsNamespace}", modelsNamespace) content = content.Replace("{ModelsNamespace}", modelsNamespace)
.Replace("{TableNameDesc}", modelTypeDesc) .Replace("{TableNameDesc}", modelTypeDesc)
@ -490,7 +375,7 @@ namespace ZR.CodeGenerator
/// <param name="vueViewSaveBindContent"></param> /// <param name="vueViewSaveBindContent"></param>
/// <param name="vueViewEditFromRuleContent"></param> /// <param name="vueViewEditFromRuleContent"></param>
/// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param> /// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param>
private static Tuple<string, string> GenerateVueViews(string modelTypeName, string primaryKey, string modelTypeDesc, string vueViewListContent, string vueViewFromContent, string vueViewEditFromContent, string vueViewEditFromBindContent, string vueViewSaveBindContent, string vueViewEditFromRuleContent, bool ifExsitedCovered = false) private static Tuple<string, string> GenerateVueViews(string modelTypeName, string primaryKey, string modelTypeDesc, string vueViewListContent, string vueViewFromContent, string vueViewEditFromContent, string vueViewEditFromBindContent, string vueViewSaveBindContent, string vueViewEditFromRuleContent, string vueJsMethod, bool ifExsitedCovered = false)
{ {
//var parentPath = "..\\CodeGenerate";//若要生成到项目中将路径改成 “..\\ZR.Vue\\src” //var parentPath = "..\\CodeGenerate";//若要生成到项目中将路径改成 “..\\ZR.Vue\\src”
var parentPath = "..\\ZR.Vue\\src"; var parentPath = "..\\ZR.Vue\\src";
@ -510,9 +395,10 @@ namespace ZR.CodeGenerator
.Replace("{VueViewFormContent}", vueViewFromContent)//添加、修改表单 .Replace("{VueViewFormContent}", vueViewFromContent)//添加、修改表单
.Replace("{ModelTypeName}", modelTypeName) .Replace("{ModelTypeName}", modelTypeName)
.Replace("{Permission}", modelTypeName.ToLower()) .Replace("{Permission}", modelTypeName.ToLower())
.Replace("{VueViewEditFormContent}", vueViewEditFromContent)//重置表单 .Replace("{VueViewEditFormContent}", vueViewEditFromContent)
//.Replace("{VueViewEditFromBindContent}", vueViewEditFromBindContent) .Replace("{vueJsMethod}", vueJsMethod)
//.Replace("{VueViewSaveBindContent}", vueViewSaveBindContent) //.Replace("{VueViewEditFromBindContent}", vueViewEditFromBindContent)
//.Replace("{VueViewSaveBindContent}", vueViewSaveBindContent)
.Replace("{primaryKey}", FirstLowerCase(primaryKey)) .Replace("{primaryKey}", FirstLowerCase(primaryKey))
.Replace("{VueViewEditFormRuleContent}", vueViewEditFromRuleContent);//添加、修改表单验证规则 .Replace("{VueViewEditFormRuleContent}", vueViewEditFromRuleContent);//添加、修改表单验证规则
WriteAndSave(fullPath, content); WriteAndSave(fullPath, content);
@ -537,13 +423,12 @@ namespace ZR.CodeGenerator
#region #region
/// <summary> /// <summary>
/// 如果有前缀替换将前缀替换成空,替换下划线"_"为空再将首字母大写 /// 如果有前缀替换将前缀替换成空,替换下划线"_"为空再将首字母大写
/// </summary> /// </summary>
/// <param name="modelTypeName"></param> /// <param name="modelTypeName"></param>
/// <returns></returns> /// <returns></returns>
private static string GetModelClassName(string modelTypeName) public static string GetModelClassName(string modelTypeName)
{ {
if (!string.IsNullOrEmpty(_option.ReplaceTableNameStr)) if (!string.IsNullOrEmpty(_option.ReplaceTableNameStr))
{ {
@ -558,7 +443,7 @@ namespace ZR.CodeGenerator
/// </summary> /// </summary>
/// <param name="str"></param> /// <param name="str"></param>
/// <returns></returns> /// <returns></returns>
private static string FirstLowerCase(string str) public static string FirstLowerCase(string str)
{ {
return string.IsNullOrEmpty(str) ? str : str.Substring(0, 1).ToLower() + str[1..]; return string.IsNullOrEmpty(str) ? str : str.Substring(0, 1).ToLower() + str[1..];
} }
@ -569,7 +454,7 @@ namespace ZR.CodeGenerator
/// <param name="columnDescription"></param> /// <param name="columnDescription"></param>
/// <param name="columnName"></param> /// <param name="columnName"></param>
/// <returns></returns> /// <returns></returns>
private static string GetLabelName(string columnDescription, string columnName) public static string GetLabelName(string columnDescription, string columnName)
{ {
return string.IsNullOrEmpty(columnDescription) ? columnName : columnDescription; return string.IsNullOrEmpty(columnDescription) ? columnName : columnDescription;
} }

View File

@ -31,7 +31,7 @@ namespace ZR.CodeGenerator.Service
var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true); var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true);
if (!string.IsNullOrEmpty(tableName)) if (!string.IsNullOrEmpty(tableName))
{ {
tableList = tableList.Where(f => f.Name.Contains(tableName)).ToList(); tableList = tableList.Where(f => f.Name.ToLower().Contains(tableName.ToLower())).ToList();
} }
pager.TotalNum = tableList.Count; pager.TotalNum = tableList.Count;
return tableList.Skip(pager.PageSize * (pager.PageNum - 1)).Take(pager.PageSize).OrderBy(f => f.Name).ToList(); return tableList.Skip(pager.PageSize * (pager.PageNum - 1)).Take(pager.PageSize).OrderBy(f => f.Name).ToList();

View File

@ -25,7 +25,7 @@
"clipboard": "2.0.4", "clipboard": "2.0.4",
"core-js": "3.6.5", "core-js": "3.6.5",
"echarts": "^5.1.1", "echarts": "^5.1.1",
"element-ui": "2.13.2", "element-ui": "2.15.6",
"file-saver": "2.0.1", "file-saver": "2.0.1",
"fuse.js": "3.4.4", "fuse.js": "3.4.4",
"js-beautify": "1.10.2", "js-beautify": "1.10.2",

View File

@ -480,3 +480,17 @@ aside {
position: relative; position: relative;
float: right; float: right;
} }
.icon {
width: 100px;
}
// 上传文件按钮样式
.uploader-icon {
width: 50px;
height: 50px;
line-height: 50px;
border: 1px dashed #ccc;
margin-bottom: 10px;
}
.table-td-thumb {
width: 80px;
}

View File

@ -44,7 +44,7 @@ export const constantRoutes = [
}, },
{ {
path: '/demo', path: '/demo',
component: (resolve) => require(['@/views/gendemo/index'], resolve), component: (resolve) => require(['@/views/userInfo/index'], resolve),
hidden: true hidden: true
}, },
{ {

View File

@ -87,35 +87,41 @@
<!-- 添加或修改菜单对话框 --> <!-- 添加或修改菜单对话框 -->
<el-dialog :title="title" :visible.sync="open" width="600px" append-to-body> <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="80px"> <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<el-row>
<el-col :span="12"> <el-form-item label="主键" prop="userId">
<el-form-item label="用户Id" prop="userId"> <el-input v-model.number="form.userId" placeholder="" :disabled="form.userId > 0" />
<el-input v-model.number="form.userId" placeholder="" :disabled="form.userId > 0" /> </el-form-item>
</el-form-item>
</el-col> <el-form-item label="单行文本" prop="name">
<el-col :span="12"> <el-input v-model="form.name" placeholder="" />
<el-form-item label="用户昵称" prop="name"> </el-form-item>
<el-input v-model="form.name" placeholder="" />
</el-form-item> <el-form-item label="number" prop="sortId">
</el-col> <el-input-number v-model="form.sortId" controls-position="right" :min="0" />
<el-col :span="12"> </el-form-item>
<el-form-item label="顺序" prop="sortId">
<el-input-number v-model="form.sortId" controls-position="right" :min="0" /> <el-form-item label="单选按钮" prop="status">
</el-form-item> <el-radio-group v-model="form.status">
</el-col> <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}</el-radio>
<el-col :span="12"> </el-radio-group>
<el-form-item label="状态" prop="status"> </el-form-item>
<el-radio-group v-model="form.status">
<el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}</el-radio> <el-form-item label="photo" :label-width="labelWidth" prop="photo">
</el-radio-group> <el-upload class="avatar-uploader" action="/api/upload/saveFile/" :show-file-list="false" :on-success="handleFileSuccess" :before-upload="beforeFileUpload">
</el-form-item> <img v-if="form.photo" :src="form.photo" class="icon">
</el-col> <i v-else class="el-icon-plus uploader-icon"></i>
<el-col :span="24"> </el-upload>
<el-form-item label="备注" prop="content"> <el-input v-model="form.photo"></el-input>
<el-input v-model="form.content" :rows="2" type="textarea" placeholder="请输入内容" /> </el-form-item>
</el-form-item>
</el-col> <el-form-item label="时间控件" :label-width="labelWidth" prop="lastLoginTime">
</el-row> <el-date-picker v-model="form.lastLoginTime" type="datetime" placeholder="选择日期时间" default-time="12:00:00"> </el-date-picker>
</el-form-item>
<el-form-item label="多行文本" prop="content">
<el-input v-model="form.content" :rows="2" type="textarea" placeholder="请输入内容" />
</el-form-item>
</el-form> </el-form>
<div slot="footer" class="dialog-footer" v-if="btnSubmitVisible"> <div slot="footer" class="dialog-footer" v-if="btnSubmitVisible">
<el-button type="primary" @click="submitForm"> </el-button> <el-button type="primary" @click="submitForm"> </el-button>
@ -132,7 +138,7 @@ export default {
name: "demo", name: "demo",
data() { data() {
return { return {
labelWidth: "70px", labelWidth: "100px",
// //
loading: true, loading: true,
// //

View File

@ -1,44 +1,42 @@
<template> <template>
<div class="app-container"> <div class="app-container">
<el-card>
<div> <el-form ref="codeform" :inline="true" :rules="rules" :model="codeform" size="small">
<el-form ref="codeform" :inline="true" :rules="rules" :model="codeform" size="small"> <el-form-item label="数据库" prop="dbName">
<el-form-item label="数据库" prop="dbName"> <el-select v-model="codeform.dbName" clearable placeholder="请选择" @change="handleShowTable">
<el-select v-model="codeform.dbName" clearable placeholder="请选择" @change="handleShowTable"> <el-option v-for="item in selectedDataBase" :key="item" :label="item" :value="item" />
<el-option v-for="item in selectedDataBase" :key="item" :label="item" :value="item" /> </el-select>
</el-select> </el-form-item>
</el-form-item> <el-form-item label="表名">
<el-form-item label="表名"> <el-input v-model="codeform.tableName" clearable placeholder="输入要查询的表名" />
<el-input v-model="codeform.tableName" clearable placeholder="输入要查询的表名" /> </el-form-item>
</el-form-item> <!-- <el-form-item label="项目命名空间:" prop="baseSpace">
<!-- <el-form-item label="项目命名空间:" prop="baseSpace">
<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="codeform.baseSpace" clearable placeholder="如Zr" /> <el-input v-model="codeform.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="codeform.replaceTableNameStr" clearable width="300" placeholder="例如sys_" /> <el-input v-model="codeform.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>
</el-form-item> </el-form-item>
</el-form> </el-form>
</div>
<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 stripe highlight-current-row height="500px" style="width: 100%;">
<el-table-column prop="name" label="表名" sortable="custom" width="380" /> <el-table-column prop="name" label="表名" sortable="custom" width="380" />
<el-table-column prop="description" label="表描述" /> <el-table-column prop="description" label="表描述" />
<el-table-column label="操作" align="center" width="200"> <el-table-column label="操作" align="center" width="200">
<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-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>
</el-table> </el-table>
<el-pagination background :current-page="pagination.pageNum" :page-sizes="[5,10,20,50,100, 200, 300, 400]" :page-size="pagination.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.pageTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange" /> <el-pagination background :current-page="pagination.pageNum" :page-sizes="[5,10,20,50,100, 200, 300, 400]" :page-size="pagination.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="pagination.pageTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
</el-card>
<el-dialog :visible.sync="showGenerate" title="代码生成" width="800px"> <el-dialog :visible.sync="showGenerate" title="代码生成" width="800px">
<el-form ref="codeGenerateForm" label-width="140px"> <el-form ref="codeGenerateForm" label-width="140px">

View File

@ -920,5 +920,46 @@
</summary> </summary>
<param name="services"></param> <param name="services"></param>
</member> </member>
<member name="T:ZRAdmin.Controllers.UserInfoController">
<summary>
代码自动生成
</summary>
</member>
<member name="F:ZRAdmin.Controllers.UserInfoController._UserInfoService">
<summary>
接口
</summary>
</member>
<member name="M:ZRAdmin.Controllers.UserInfoController.Query(ZR.Model.Dto.UserInfoQueryDto)">
<summary>
查询列表
</summary>
<returns></returns>
</member>
<member name="M:ZRAdmin.Controllers.UserInfoController.Get(System.Int32)">
<summary>
查询详情
</summary>
<param name="Luid"></param>
<returns></returns>
</member>
<member name="M:ZRAdmin.Controllers.UserInfoController.Create(ZR.Model.Dto.UserInfoDto)">
<summary>
添加
</summary>
<returns></returns>
</member>
<member name="M:ZRAdmin.Controllers.UserInfoController.Update(ZR.Model.Dto.UserInfoDto)">
<summary>
更新
</summary>
<returns></returns>
</member>
<member name="M:ZRAdmin.Controllers.UserInfoController.Delete(System.Int32)">
<summary>
删除
</summary>
<returns></returns>
</member>
</members> </members>
</doc> </doc>