开发代码生成功能

This commit is contained in:
izory 2021-09-07 21:52:44 +08:00
parent 18d8051d65
commit 85b0305cbc
11 changed files with 131 additions and 312 deletions

View File

@ -9,6 +9,7 @@ namespace Infrastructure
public static string ConnAdmin = "Conn_admin";
public static string Conn = "ConnDynamic";
public static string DbType = "DbType";
public static string CodeGenDbType = "CodeGenDbType";
public static string DbKey = "DbKey";
public string Conn_Admin { get; set; }

View File

@ -3,6 +3,7 @@ using Infrastructure.Attribute;
using Infrastructure.Enums;
using Infrastructure.Model;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
@ -74,20 +75,18 @@ namespace ZR.Admin.WebApi.Controllers
[Log(Title = "代码生成", BusinessType = BusinessType.OTHER)]
public IActionResult Generate(string dbName, string baseSpace, string tables, string replaceTableNameStr)
{
if (string.IsNullOrEmpty(tables))
{
throw new CustomException(ResultCode.CUSTOM_ERROR, "请求参数为空");
}
if (string.IsNullOrEmpty(baseSpace))
{
throw new CustomException(ResultCode.CUSTOM_ERROR, "命名空间不能为空");
}
string[] tableList = tables.Split(",");
List<DbTableInfo> tableInfos = new List<DbTableInfo>();// CodeGeneratorService.GetAllTables(tables);
foreach (var item in tableList)
{
tableInfos.Add(new DbTableInfo() { TableName = item });
//baseSpace = "Zr";
}
DbTableInfo dbTableInfo = new() { Name = tables };
CodeGeneratorTool.Generate(dbName, baseSpace, dbTableInfo, replaceTableNameStr, true);
CodeGeneratorTool.Generate(dbName, baseSpace, tableInfos, replaceTableNameStr, true);
return SUCCESS(null);
return SUCCESS(1);
}
}
}

View File

@ -6,7 +6,6 @@
"Microsoft.Hosting.Lifetime": "Information"
}
},
"appName": "ZR Admin System",
"ConnectionStrings": {
"Conn_Admin": "server=127.0.0.1;database=admin;user=zr;pwd=abc"
},

View File

@ -6,7 +6,6 @@
"Microsoft.Hosting.Lifetime": "Information"
}
},
"appName": "ZR Admin system",
"ConnectionStrings": {
"Conn_Admin": "server=127.0.0.1;database=admin;user=zr;pwd=abc"
},

View File

@ -1,4 +1,5 @@
using System;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
@ -32,47 +33,44 @@ namespace ZR.CodeGenerator
/// 代码生成器入口方法
/// </summary>
/// <param name="baseNamespace"></param>
/// <param name="tableList">要生成代码的表</param>
/// <param name="listTable"></param>
/// <param name="listField"></param>
/// <param name="dbTableInfo"></param>
/// <param name="replaceTableNameStr">要删除表名称的字符</param>
/// <param name="ifExsitedCovered">是否替换现有文件为true时替换</param>
public static void Generate(string dbName, string baseNamespace, List<DbTableInfo> listTable, string replaceTableNameStr, bool ifExsitedCovered = false)
public static void Generate(string dbName, string baseNamespace, DbTableInfo dbTableInfo, string replaceTableNameStr, bool ifExsitedCovered = false)
{
_option.DtosNamespace = baseNamespace + ".Dtos";
_option.ModelsNamespace = baseNamespace + ".Model";
_option.IRepositoriesNamespace = baseNamespace + ".IRepositories";
_option.RepositoriesNamespace = baseNamespace + ".Repositories";
_option.IServicsNamespace = baseNamespace + ".IServices";
_option.ServicesNamespace = baseNamespace + ".Services";
_option.BaseNamespace = baseNamespace;
_option.DtosNamespace = baseNamespace + "ZR.Model.Dto";
_option.ModelsNamespace = baseNamespace + "ZR.Model";
//_option.IRepositoriesNamespace = baseNamespace + ".IRepositorie";
_option.RepositoriesNamespace = baseNamespace + "ZR.Repository";
//_option.IServicsNamespace = baseNamespace + ".IService";
_option.ServicesNamespace = baseNamespace + "ZR.Service";
_option.ApiControllerNamespace = baseNamespace + "Api";
_option.ReplaceTableNameStr = replaceTableNameStr;
//_option.TableList = listTable;
_option.BaseNamespace = baseNamespace;
CodeGeneraterService codeGeneraterService = new CodeGeneraterService();
//List<DbTableInfo> listTable = dbExtractor.GetWhereTables(_option.TableList);
string profileContent = string.Empty;
foreach (DbTableInfo dbTableInfo in listTable)
{
List<SqlSugar.DbColumnInfo> listField = codeGeneraterService.GetColumnInfo(dbName, dbTableInfo.TableName);
GenerateSingle(listField, dbTableInfo, ifExsitedCovered);
string tableName = dbTableInfo.TableName;
if (!string.IsNullOrEmpty(_option.ReplaceTableNameStr))
{
string[] rel = _option.ReplaceTableNameStr.Split(';');
for (int i = 0; i < rel.Length; i++)
{
if (!string.IsNullOrEmpty(rel[i].ToString()))
{
tableName = tableName.Replace(rel[i].ToString(), "");
}
}
}
tableName = tableName.Substring(0, 1).ToUpper() + tableName.Substring(1);
profileContent += string.Format(" CreateMap<{0}, {0}OutputDto>();\n", tableName);
profileContent += string.Format(" CreateMap<{0}InputDto, {0}>();\n", tableName);
}
//foreach (DbTableInfo dbTableInfo in listTable)
//{
List<DbColumnInfo> listField = codeGeneraterService.GetColumnInfo(dbName, dbTableInfo.Name);
GenerateSingle(listField, dbTableInfo, ifExsitedCovered);
//string tableName = dbTableInfo.TableName;
//if (!string.IsNullOrEmpty(_option.ReplaceTableNameStr))
//{
// string[] rel = _option.ReplaceTableNameStr.Split(';');
// for (int i = 0; i < rel.Length; i++)
// {
// if (!string.IsNullOrEmpty(rel[i].ToString()))
// {
// tableName = tableName.Replace(rel[i].ToString(), "");
// }
// }
//}
//tableName = tableName.Substring(0, 1).ToUpper() + tableName.Substring(1);
//profileContent += string.Format(" CreateMap<{0}, {0}OutputDto>();\n", tableName);
//profileContent += string.Format(" CreateMap<{0}InputDto, {0}>();\n", tableName);
//}
//GenerateDtoProfile(_option.ModelsNamespace, profileContent, ifExsitedCovered);
}
@ -85,23 +83,18 @@ namespace ZR.CodeGenerator
/// <param name="listField">表字段集合</param>
/// <param name="tableInfo">表信息</param>
/// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param>
public static void GenerateSingle(List<SqlSugar.DbColumnInfo> listField, DbTableInfo tableInfo, bool ifExsitedCovered = false)
public static void GenerateSingle(List<DbColumnInfo> listField, DbTableInfo tableInfo, bool ifExsitedCovered = false)
{
var modelsNamespace = _option.ModelsNamespace;
var modelTypeName = tableInfo.TableName;//表名
var modelTypeName = tableInfo.Name;//表名
var modelTypeDesc = tableInfo.Description;//表描述
if (!string.IsNullOrEmpty(_option.ReplaceTableNameStr))
{
string[] rel = _option.ReplaceTableNameStr.Split(';');
for (int i = 0; i < rel.Length; i++)
{
if (!string.IsNullOrEmpty(rel[i].ToString()))
{
modelTypeName = modelTypeName.Replace(rel[i].ToString(), "");
}
}
modelTypeName = modelTypeName.Replace(_option.ReplaceTableNameStr.ToString(), "");
}
modelTypeName = modelTypeName.Replace("_", "");
modelTypeName = modelTypeName.Substring(0, 1).ToUpper() + modelTypeName.Substring(1);
string keyTypeName = "string";//主键数据类型
string modelcontent = "";//数据库模型字段
string InputDtocontent = "";//输入模型
@ -113,23 +106,25 @@ namespace ZR.CodeGenerator
string vueViewSaveBindContent = string.Empty;//Vue保存时输出内容
string vueViewEditFromRuleContent = string.Empty;//Vue数据校验
foreach (SqlSugar.DbColumnInfo dbFieldInfo in listField)
foreach (DbColumnInfo dbFieldInfo in listField)
{
string columnName = dbFieldInfo.DbColumnName.Substring(0, 1).ToUpper() + dbFieldInfo.DbColumnName.Substring(1);
modelcontent += " /// <summary>\n";
modelcontent += ($" /// {dbFieldInfo.ColumnDescription}\n");
modelcontent += ($" /// 描述 :{dbFieldInfo.ColumnDescription}\n");
modelcontent += ($" /// 空值 :{dbFieldInfo.IsNullable}\n");
modelcontent += ($" /// 默认 :{dbFieldInfo.DefaultValue}\n");
modelcontent += " /// </summary>\n";
if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey)
{
modelcontent += $" [SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPrimarykey}, IsIdentity = {dbFieldInfo.IsIdentity})]\n";
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";
//主键
if (dbFieldInfo.IsIdentity)
{
keyTypeName = dbFieldInfo.DataType;
//if (dbFieldInfo.IsIdentity)
//{
//keyTypeName = dbFieldInfo.DataType;
//outputDtocontent += " /// <summary>\n";
//outputDtocontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription);
//outputDtocontent += " /// </summary>\n";
@ -137,18 +132,18 @@ namespace ZR.CodeGenerator
//outputDtocontent += string.Format(" [SqlSugar.SugarColumn(IsIdentity = true, IsPrimaryKey = true)]\n");
//outputDtocontent += string.Format(" public {0} {1}", TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType), columnName);
//outputDtocontent += " { get; set; }\n\r";
}
else //非主键
{
modelcontent += " /// <summary>\n";
modelcontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription);
modelcontent += " /// </summary>\n";
//if (dbFieldInfo.DataType == "string")
//{
// modelcontent += string.Format(" [MaxLength({0})]\n", dbFieldInfo.FieldMaxLength);
//}
modelcontent += string.Format(" public {0} {1}", TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType), columnName);
modelcontent += " { get; set; }\n\r";
//}
// else //非主键
//{
//modelcontent += " /// <summary>\n";
//modelcontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription);
//modelcontent += " /// </summary>\n";
////if (dbFieldInfo.DataType == "string")
////{
//// modelcontent += string.Format(" [MaxLength({0})]\n", dbFieldInfo.FieldMaxLength);
////}
//modelcontent += string.Format(" public {0} {1}", TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType), columnName);
//modelcontent += " { get; set; }\n\r";
//outputDtocontent += " /// <summary>\n";
@ -216,8 +211,8 @@ namespace ZR.CodeGenerator
// InputDtocontent += " { get; set; }\n\r";
//}
//
}
GenerateModels(modelsNamespace, modelTypeName, tableInfo.TableName, modelcontent, modelTypeDesc, keyTypeName, ifExsitedCovered);
//}
GenerateModels(modelsNamespace, modelTypeName, tableInfo.Name, modelcontent, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateRepository(modelTypeName, modelTypeDesc, tableInfo.TableName, keyTypeName, ifExsitedCovered);
//GenerateIService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
@ -243,16 +238,14 @@ namespace ZR.CodeGenerator
/// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param>
private static void GenerateModels(string modelsNamespace, string modelTypeName, string tableName, string modelContent, string modelTypeDesc, string keyTypeName, bool ifExsitedCovered = false)
{
var path = AppDomain.CurrentDomain.BaseDirectory;
//path = path.Substring(0, path.IndexOf("\\bin"));
var parentPath = path.Substring(0, path.LastIndexOf("\\"));
var servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + modelsNamespace;
var parentPath = "..\\";
var servicesPath = parentPath + _option.BaseNamespace + "\\" + modelsNamespace;
if (!Directory.Exists(servicesPath))
{
servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\Models";
servicesPath = parentPath + _option.ModelsNamespace;
Directory.CreateDirectory(servicesPath);
}
var fullPath = servicesPath + "\\" + modelTypeName + ".cs";
var fullPath = servicesPath + "\\Models\\" + modelTypeName + ".cs";
if (File.Exists(fullPath) && !ifExsitedCovered)
return;
var content = ReadTemplate("ModelTemplate.txt");

View File

@ -14,7 +14,7 @@ namespace ZR.CodeGenerator
public SqlSugarClient GetSugarDbContext(string dbName)
{
string connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.Conn).Replace("{DbName}", dbName);
int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.DbType, 0);
int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.CodeGenDbType, 0);
return new SqlSugarClient(new List<ConnectionConfig>()
{

View File

@ -12,24 +12,6 @@ namespace ZR.CodeGenerator.Service
{
public class CodeGeneraterService: DbProvider
{
///// <summary>
///// 获取表所有列
///// </summary>
///// <param name="tableName"></param>
///// <returns></returns>
//public List<DbFieldInfo> GetAllColumns(string tableName)
//{
// var dbType = ConfigUtils.Instance.GetConfig("CodeGenDbType");
// if (tableName == null)
// throw new ArgumentException(nameof(tableName));
// List<DbFieldInfo> list = new List<DbFieldInfo>();
// if (dbType == "1")
// {
// list = CodeGeneratorRepository.GetAllColumns(tableName);
// }
// return list;
//}
/// <summary>
/// 获取所有数据库名
/// </summary>
@ -59,7 +41,6 @@ namespace ZR.CodeGenerator.Service
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <param name="tableStrs"></param>
/// <param name="pager"></param>
/// <returns></returns>
public List<SqlSugar.DbTableInfo> GetAllTables(string dbName, string tableName, PagerInfo pager)

View File

@ -1,79 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace ZR.Model
{
/// <summary>
/// 表的字段
/// </summary>
public class DbFieldInfo
{
public string TableName { get; set; }
/// <summary>
/// 初始化
/// </summary>
public DbFieldInfo()
{
FieldName = string.Empty;
Description = string.Empty;
}
/// <summary>
/// 字段名称
/// </summary>
public string FieldName { get; set; }
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 系统数据类型,如 int
/// </summary>
public string DataType
{
get;
set;
}
/// <summary>
/// 数据库里面存放的类型。
/// </summary>
public string FieldType { get; set; }
/// <summary>
/// 代表小数位精度。
/// </summary>
public long? FieldScale { get; set; }
/// <summary>
/// 数据精度仅数字类型有效总共多少位数字10进制
/// 在MySql里面代表了字段长度
/// </summary>
public long? FieldPrecision { get; set; }
/// <summary>
///
/// </summary>
public long? FieldMaxLength { get; set; }
/// <summary>
/// 可空
/// </summary>
public bool IsNullable { get; set; }
/// <summary>
/// 是否为主键字段
/// </summary>
public bool IsIdentity { get; set; }
/// <summary>
/// 【未用上】该字段是否自增
/// </summary>
public bool Increment { get; set; }
/// <summary>
/// 默认值
/// </summary>
public string FieldDefaultValue { get; set; }
}
}

View File

@ -1,75 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ZR.Model
{
/// <summary>
/// 数据表的信息
/// </summary>
public class DbTableInfo
{
/// <summary>
/// 表格ID表的名称。
/// </summary>
public string TableName { get; set; }
/// <summary>
/// 表的别称,或者描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 字段列表
/// </summary>
public List<DbFieldInfo> Fileds { get; set; }
/// <summary>
/// 初始化
/// </summary>
public DbTableInfo()
{
Fileds = new List<DbFieldInfo>();
}
/// <summary>
/// 获取主键的名称列表。
/// </summary>
/// <returns></returns>
public List<string> GetIdentityList()
{
var list = Fileds.Where(x => x.IsIdentity);
if (list == null) return null;
return list.Select(x => x.FieldName).ToList();
}
/// <summary>
/// 获取主键字段列表
/// </summary>
/// <returns></returns>
public List<DbFieldInfo> GetIdentityFields()
{
var list = Fileds.Where(x => x.IsIdentity);
if (list == null) return null;
return list.ToList();
}
/// <summary>
/// 获取可空字段。
/// </summary>
/// <returns></returns>
public List<DbFieldInfo> GetIsNullableFields()
{
var list = Fileds.Where(x => x.IsNullable);
if (list == null) return null;
return list.ToList();
}
/// <summary>
/// 获取不可空字段。
/// </summary>
/// <returns></returns>
public List<DbFieldInfo> GetNotNullableFields()
{
var list = Fileds.Where(x => !x.IsNullable);
if (list == null) return null;
return list.ToList();
}
}
}

View File

@ -1,4 +1,5 @@
using Infrastructure.Attribute;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
@ -12,50 +13,50 @@ namespace ZR.Repository.System
[AppService(ServiceLifetime = LifeTime.Transient)]
public class CodeGeneratorRepository : BaseRepository
{
/// <summary>
/// 获取数据库
/// </summary>
/// <returns></returns>
public List<DataBaseInfo> GetAllDb()
{
//return Db.Ado.SqlQuery<DataBaseInfo>("select name as DbName from master..sysdatabases ");
var list = Db.DbMaintenance.GetDataBaseList(Db);
List<DataBaseInfo> dataBases = new List<DataBaseInfo>();
list.ForEach(item =>
{
dataBases.Add(new DataBaseInfo() { DbName = item });
});
return dataBases;
}
///// <summary>
///// 获取数据库
///// </summary>
///// <returns></returns>
//public List<DataBaseInfo> GetAllDb()
//{
// //return Db.Ado.SqlQuery<DataBaseInfo>("select name as DbName from master..sysdatabases ");
// var list = Db.DbMaintenance.GetDataBaseList(Db);
// List<DataBaseInfo> dataBases = new List<DataBaseInfo>();
// list.ForEach(item =>
// {
// dataBases.Add(new DataBaseInfo() { DbName = item });
// });
// return dataBases;
//}
/// <summary>
/// 根据数据库名获取所有的表
/// </summary>
/// <param name="dbName"></param>
/// <param name="pager"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public List<SqlSugar.DbTableInfo> GetAllTables(string dbName, string tableName, PagerInfo pager)
{
var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true);
if (!string.IsNullOrEmpty(tableName))
{
tableList = tableList.Where(f => f.Name.Contains(tableName)).ToList();
}
pager.TotalNum = tableList.Count;
return tableList.Skip(pager.PageSize * (pager.PageNum - 1)).Take(pager.PageSize).OrderBy(f => f.Name).ToList();
}
///// <summary>
///// 根据数据库名获取所有的表
///// </summary>
///// <param name="dbName"></param>
///// <param name="pager"></param>
///// <param name="tableName"></param>
///// <returns></returns>
//public List<SqlSugar.DbTableInfo> GetAllTables(string dbName, string tableName, PagerInfo pager)
//{
// var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true);
// if (!string.IsNullOrEmpty(tableName))
// {
// tableList = tableList.Where(f => f.Name.Contains(tableName)).ToList();
// }
// pager.TotalNum = tableList.Count;
// return tableList.Skip(pager.PageSize * (pager.PageNum - 1)).Take(pager.PageSize).OrderBy(f => f.Name).ToList();
//}
/// <summary>
/// 获取表格列信息
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <returns></returns>
public List<SqlSugar.DbColumnInfo> GetColumnInfo(string dbName, string tableName)
{
return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true);
}
///// <summary>
///// 获取表格列信息
///// </summary>
///// <param name="dbName"></param>
///// <param name="tableName"></param>
///// <returns></returns>
//public List<SqlSugar.DbColumnInfo> GetColumnInfo(string dbName, string tableName)
//{
// return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true);
//}
/// <summary>
@ -63,12 +64,12 @@ namespace ZR.Repository.System
/// </summary>
/// <param name="tabList"></param>
/// <returns></returns>
public List<DbTableInfo> GetAllTables(string[] tabList)
{
string sql = @"SELECT tbs.name as TableName ,ds.value as Description FROM sys.tables tbs
left join sys.extended_properties ds on ds.major_id=tbs.object_id and ds.minor_id=0";
//public List<DbTableInfo> GetAllTables(string[] tabList)
//{
// string sql = @"SELECT tbs.name as TableName ,ds.value as Description FROM sys.tables tbs
// left join sys.extended_properties ds on ds.major_id=tbs.object_id and ds.minor_id=0";
return Db.SqlQueryable<DbTableInfo>(sql).WhereIF(tabList.Length > 0, x => tabList.Contains(x.TableName)).ToList();
}
// return Db.SqlQueryable<DbTableInfo>(sql).WhereIF(tabList.Length > 0, x => tabList.Contains(x.TableName)).ToList();
//}
}
}

View File

@ -113,15 +113,15 @@ export default {
replaceTableNameStr: "",
},
rules: {
baseSpace: [
{ required: true, message: "请输入项目名称", trigger: "blur" },
{
min: 2,
max: 50,
message: "长度在 2 到 50 个字符",
trigger: "blur",
},
],
// baseSpace: [
// { required: true, message: "", trigger: "blur" },
// {
// min: 2,
// max: 50,
// message: " 2 50 ",
// trigger: "blur",
// },
// ],
replaceTableNameStr: [
{ min: 0, max: 50, message: "长度小于50个字符", trigger: "blur" },
],