代码生成增加service、Repository、Controller层

This commit is contained in:
izory 2021-09-08 18:12:08 +08:00
parent 2d72257945
commit 8478df3a11
17 changed files with 897 additions and 288 deletions

View File

@ -37,7 +37,6 @@ namespace ZR.Admin.WebApi.Controllers
/// <returns></returns> /// <returns></returns>
[HttpGet("GetListDataBase")] [HttpGet("GetListDataBase")]
//[YuebonAuthorize("GetListDataBase")] //[YuebonAuthorize("GetListDataBase")]
//[NoPermissionRequired]
public IActionResult GetListDataBase() public IActionResult GetListDataBase()
{ {
return SUCCESS(_CodeGeneraterService.GetAllDataBases()); return SUCCESS(_CodeGeneraterService.GetAllDataBases());
@ -53,12 +52,8 @@ namespace ZR.Admin.WebApi.Controllers
[HttpGet("FindListTable")] [HttpGet("FindListTable")]
public IActionResult FindListTable(string dbName, string tableName, PagerInfo pager) public IActionResult FindListTable(string dbName, string tableName, PagerInfo pager)
{ {
if (string.IsNullOrEmpty(dbName)) List<DbTableInfo> list = _CodeGeneraterService.GetAllTables(dbName, tableName, pager);
{ var vm = new VMPageResult<DbTableInfo>(list, pager);
dbName = "ZrAdmin";
}
List<SqlSugar.DbTableInfo> list = _CodeGeneraterService.GetAllTables(dbName, tableName, pager);
var vm = new VMPageResult<SqlSugar.DbTableInfo>(list, pager);
return SUCCESS(vm); return SUCCESS(vm);
} }
@ -81,7 +76,7 @@ namespace ZR.Admin.WebApi.Controllers
} }
if (string.IsNullOrEmpty(baseSpace)) if (string.IsNullOrEmpty(baseSpace))
{ {
//baseSpace = "Zr"; baseSpace = "ZR.Admin";
} }
DbTableInfo dbTableInfo = new() { Name = tables }; DbTableInfo dbTableInfo = new() { Name = tables };
CodeGeneratorTool.Generate(dbName, baseSpace, dbTableInfo, replaceTableNameStr, true); CodeGeneratorTool.Generate(dbName, baseSpace, dbTableInfo, replaceTableNameStr, true);

View File

@ -10,13 +10,13 @@ namespace ZR.Admin.WebApi.Extensions
{ {
var types = source.GetType(); var types = source.GetType();
var worker = new IdWorker(1, 1); //var worker = new IdWorker(1, 1);
if (types.GetProperty("ID") != null) //if (types.GetProperty("ID") != null)
{ //{
long id = worker.NextId(); // long id = worker.NextId();
types.GetProperty("ID").SetValue(source, id.ToString(), null); // types.GetProperty("ID").SetValue(source, id.ToString(), null);
} //}
if (types.GetProperty("CreateTime") != null) if (types.GetProperty("CreateTime") != null)
{ {

View File

@ -0,0 +1,124 @@
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ZR.Admin.WebApi.Filters;
using ZR.Admin.WebApi.Controllers;
using ZR.Service;
using SqlSugar;
using Infrastructure;
using Infrastructure.Attribute;
using Infrastructure.Enums;
using Infrastructure.Model;
using Mapster;
using ZR.Admin.WebApi.Extensions;
using ZR.Model;
namespace ZRAdmin.Controllers
{
/// <summary>
/// T4代码自动生成
/// </summary>
[Verify]
[Route("bus/<#=ModelName#>")]
public class <#=ControllerName#>Controller: BaseController
{
/// <summary>
/// <#=FileName#>接口
/// </summary>
private readonly I<#=ServiceName#> _<#=ServiceName#>;
public <#=ControllerName#>Controller(I<#=ServiceName#> <#=ServiceName#>)
{
_<#=ServiceName#> = <#=ServiceName#>;
}
/// <summary>
/// 查询<#=FileName#>列表
/// </summary>
/// <returns></returns>
[HttpGet("list")]
[ActionPermissionFilter(Permission = "<#=ModelName#>:list")]
public IActionResult Query([FromQuery] <#=ModelName#>QueryDto parm)
{
//开始拼装查询条件
var predicate = Expressionable.Create<<#=ModelName#>>();
//TODO 搜索条件
//predicate = predicate.And(m => m.Name.Contains(parm.Name));
var response = _<#=ServiceName#>.GetPages(predicate.ToExpression(), parm);
return SUCCESS(response);
}
/// <summary>
/// 查询<#=FileName#>详情
/// </summary>
/// <param name="{primaryKey}"></param>
/// <returns></returns>
[HttpGet("{{primaryKey}}")]
public IActionResult Get(int {primaryKey})
{
var response = _<#=ServiceName#>.GetId({primaryKey});
return SUCCESS(response);
}
/// <summary>
/// 添加<#=FileName#>
/// </summary>
/// <returns></returns>
[HttpPost]
[ActionPermissionFilter(Permission = "<#=ModelName#>:add")]
[Log(Title = "<#=FileName#>添加", BusinessType = BusinessType.INSERT)]
public IActionResult Create([FromBody] <#=ModelName#>Dto parm)
{
if (parm == null)
{
throw new CustomException("请求参数错误");
}
//从 Dto 映射到 实体
var addModel = parm.Adapt<<#=ModelName#>>().ToCreate();
//addModel.CreateID = User.Identity.Name;
return SUCCESS(_<#=ServiceName#>.Add(addModel));
}
/// <summary>
/// 更新<#=FileName#>
/// </summary>
/// <returns></returns>
[HttpPut("edit")]
[ActionPermissionFilter(Permission = "<#=ModelName#>:update")]
[Log(Title = "<#=FileName#>修改", BusinessType = BusinessType.UPDATE)]
public IActionResult Update([FromBody] <#=ModelName#>Dto parm)
{
//从 Dto 映射到 实体
var addModel = parm.Adapt<<#=ModelName#>>().ToCreate();
//addModel.CreateID = User.Identity.Name;
//TODO 字段映射
var response = _<#=ServiceName#>.Update(addModel);
return SUCCESS(response);
}
/// <summary>
/// 删除<#=FileName#>
/// </summary>
/// <returns></returns>
[HttpDelete("{{primaryKey}}")]
[ActionPermissionFilter(Permission = "<#=ModelName#>:delete")]
[Log(Title = "<#=FileName#>删除", BusinessType = BusinessType.DELETE)]
public IActionResult Delete(int {primaryKey} = 0)
{
if ({primaryKey} <= 0) { return OutputJson(ApiResult.Error($"删除失败Id 不能为空")); }
// 删除<#=FileName#>
var response = _<#=ServiceName#>.Delete({primaryKey});
return SUCCESS(response);
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using ZR.Model.System;
using ZR.Model;
namespace {IServicsNamespace}
{
/// <summary>
/// 定义{TableNameDesc}服务接口
/// </summary>
public interface I{ModelTypeName}Service: IBaseService<{ModelTypeName}>
{
}
}

View File

@ -0,0 +1,24 @@
using System;
using Infrastructure.Attribute;
using {RepositoriesNamespace}.System;
using {ModelsNamespace};
namespace {RepositoriesNamespace}
{
/// <summary>
/// {TableNameDesc}仓储接口的实现
/// </summary>
[AppService(ServiceLifetime = LifeTime.Transient)]
public class {ModelTypeName}Repository : BaseRepository
{
public {ModelTypeName}Repository()
{
}
#region 业务逻辑代码
#endregion
}
}

View File

@ -0,0 +1,28 @@
using Infrastructure;
using Infrastructure.Attribute;
using Infrastructure.Extensions;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZR.Common;
using ZR.Model;
using ZR.Repository;
using ZR.Service.IService;
namespace {ServicesNamespace}
{
/// <summary>
/// {TableNameDesc}服务接口实现
/// </summary>
[AppService(ServiceType = typeof(I{ModelTypeName}Service), ServiceLifetime = LifeTime.Transient)]
public class {ModelTypeName}Service: BaseService<{ModelTypeName}>, I{ModelTypeName}Service
{
private readonly {ModelTypeName}Repository _repository;
public {ModelTypeName}Service({ModelTypeName}Repository repository)
{
_repository = repository;
}
}
}

View File

@ -0,0 +1,85 @@
import http from '@/utils/request'
import defaultSettings from '@/settings'
/**
* {ModelTypeDesc}分页查询
* @param {查询条件} data
*/
export function get{ModelTypeName}ListWithPager(data) {
return http.request({
url: '{ModelTypeName}/FindWithPagerAsync',
method: 'post',
data: data,
baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式
})
}/**
* 获取所有可用的{ModelTypeDesc}
*/
export function getAll{ModelTypeName}List() {
return http.request({
url: '{ModelTypeName}/GetAllEnable',
method: 'get',
baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式
})
}
/**
* 新增或修改保存{ModelTypeDesc}
* @param data
*/
export function save{ModelTypeName}(data, url) {
return http.request({
url: url,
method: 'post',
data: data,
baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式
})
}
/**
* 获取{ModelTypeDesc}详情
* @param {Id} {ModelTypeDesc}Id
*/
export function get{ModelTypeName}Detail(id) {
return http({
url: '{ModelTypeName}/GetById',
method: 'get',
params: { id: id },
baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式
})
}
/**
* 批量设置启用状态
* @param {id集合} ids
*/
export function set{ModelTypeName}Enable(data) {
return http({
url: '{ModelTypeName}/SetEnabledMarktBatchAsync',
method: 'post',
data: data,
baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式
})
}
/**
* 批量软删除
* @param {id集合} ids
*/
export function deleteSoft{ModelTypeName}(data) {
return http({
url: '{ModelTypeName}/DeleteSoftBatchAsync',
method: 'post',
data: data,
baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式
})
}
/**
* 批量删除
* @param {id集合} ids
*/
export function delete{ModelTypeName}(data) {
return http({
url: '{ModelTypeName}/DeleteBatchAsync',
method: 'delete',
data: data,
baseURL: defaultSettings.api{fileClassName}Url // 直接通过覆盖的方式
})
}

View File

@ -0,0 +1,249 @@
<template>
<div class="app-container">
<el-row :gutter="24">
<!-- :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-col :span="6">
<el-form-item label="文本文字">
<el-input v-model="queryParams.xxx" placeholder="" />
</el-form-item>
</el-col>
<el-col :span="6">
<el-form-item label="数字">
<el-input v-model.number="queryParams.xxx" placeholder="" />
</el-form-item>
</el-col>
<el-col :span="6">
<el-form-item label="下拉框">
<el-select v-model="queryParams.xxx" placeholder="">
<el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
</el-select>
</el-form-item>
</el-col>
<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 :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button type="primary" v-hasPermi="['{ModelTypeName}:add']" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="success" v-hasPermi="['{ModelTypeName}:update']" plain icon="el-icon-edit" size="mini" @click="handleUpdate">修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="danger" v-hasPermi="['{ModelTypeName}:delete']" plain icon="el-icon-delete" size="mini" @click="handleDelete">删除</el-button>
</el-col>
<!-- <el-col :span="1.5">
<el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
</el-col>
<el-col :span="1.5">
<el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
</el-col> -->
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<!-- 数据区域 -->
<el-table :data="dataList" ref="table" border @selection-change="handleSelectionChange">
<el-table-column type="selection" width="50" />
{VueViewListContent}
<el-table-column label="操作" align="center" width="200">
<template slot-scope="scope">
<el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">详情</el-button>
<el-button size="mini" v-hasPermi="['{ModelTypeName}:update']" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑</el-button>
<el-popconfirm title="确定删除吗?" @onConfirm="handleDelete(scope.row)" style="margin-left:10px">
<el-button slot="reference" v-hasPermi="['{ModelTypeName}:del']" size="mini" type="text" icon="el-icon-delete">删除</el-button>
</el-popconfirm>
</template>
</el-table-column>
</el-table>
<pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
<!-- 添加或修改菜单对话框 -->
<el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="80px">
{VueViewFromContent}
</el-form>
<div slot="footer" class="dialog-footer" v-if="btnSubmitVisible">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
// import { list{ModelTypeName},Add{ModelTypeName},Del{ModelTypeName},Edit{ModelTypeName} } from '@/api/{ModelTypeName}.js'
export default {
name: '{ModelTypeName}',
data() {
return {
labelWidth: "70px",
// 选中数组
ids: [],
// 非多个禁用
multiple: true,
// 遮罩层
loading: true,
// 显示搜索条件
showSearch: true,
// 查询参数
queryParams: {},
// 弹出层标题
title: "",
// 是否显示弹出层
open: false,
// 表单参数
form: {},
// 时间范围数组
timeRange: [],
// xxx下拉框
statusOptions: [],
// 数据列表
dataList: [],
// 总记录数
total: 0,
// 提交按钮是否显示
btnSubmitVisible: true,
// 表单校验
rules: {
name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
userId: [
{
type: "number",
required: true,
message: "id不能为空,且不能为非数字",
trigger: "blur",
},
],
},
};
},
mounted() {
// 列表数据查询
this.getList();
// 下拉框绑定
// this.getDicts("sys_normal_disable").then((response) => {
// this.statusOptions = response.data;
// });
},
methods: {
// 查询数据
getList() {
console.log(JSON.stringify(this.queryParams));
list{ModelTypeName}(this.addDateRange(this.queryParams, this.timeRange)).then(res => {
if (res.code == 200) {
this.dataList = res.data.result;
this.total = res.data.totalCount;
}
})
},
// 取消按钮
cancel() {
this.open = false;
this.reset();
},
// 重置数据表单
reset() {
this.form = {
{VueViewEditFromContent}
//需个性化处理内容
};
this.resetForm("form");
},
/** 重置查询操作 */
resetQuery() {
this.timeRange = [];
this.resetForm("queryForm");
this.queryParams = {
pageNum: 1,
//TODO 重置字段
};
},
// 多选框选中数据
handleSelectionChange(selection) {
this.ids = selection.map((item) => item.{primaryKey});
this.multiple = !selection.length;
},
/** 搜索按钮操作 */
handleQuery() {
this.getList();
},
/** 新增按钮操作 */
handleAdd() {
this.reset();
this.open = true;
this.title = "添加";
//TODO 业务代码
},
/** 删除按钮操作 */
handleDelete(row) {
del{ModelTypeName}().then((res) => {
this.msgSuccess("删除成功");
this.handleQuery();
});
},
/** 修改按钮操作 */
handleUpdate(row) {
this.reset();
this.open = true;
this.title = "编辑";
//TODO 业务代码
console.log(JSON.stringify(row));
// TODO 给表单赋值
this.form = {
content: row.content,
userId: row.userId,
name: row.name,
sortId: row.sortId,
};
},
/** 提交按钮 */
submitForm: function () {
this.$refs["form"].validate((valid) => {
if (valid) {
console.log(JSON.stringify(this.form));
// TODO 记得改成表的主键
if (this.form.{primaryKey} != undefined) {
//TODO 编辑业务代码
} else {
//TODO 新增业务代码
}
}
});
},
// 详情
handleView(row) {
this.open = true;
this.title = "详情";
// TODO 给表单赋值
this.form = {
content: row.content,
userId: row.userId,
name: row.name,
sortId: row.sortId,
};
},
handleImport() {},
handleExport() {},
},
};
</script>
<style scoped>
.table-td-thumb {
width: 80px;
}
</style>

View File

@ -57,12 +57,30 @@
<Generator>TextTemplatingFileGenerator</Generator> <Generator>TextTemplatingFileGenerator</Generator>
<LastGenOutput>Controller.cs</LastGenOutput> <LastGenOutput>Controller.cs</LastGenOutput>
</None> </None>
<None Update="Template\ControllersTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\InputDtoTemplate.txt"> <None Update="Template\InputDtoTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
<None Update="Template\IServiceTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\ModelTemplate.txt"> <None Update="Template\ModelTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None> </None>
<None Update="Template\RepositoryTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\ServiceTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\VueJsTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Template\VueTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -70,6 +88,16 @@
<Folder Include="wwwroot\" /> <Folder Include="wwwroot\" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Resource Include="Template\RepositoryTemplate.txt" />
<Resource Include="Template\ServiceTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
<Resource Include="Template\VueJsTemplate.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Resource>
</ItemGroup>
<ItemGroup> <ItemGroup>
<Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" /> <Service Include="{508349b6-6b84-4df5-91f0-309beebad82d}" />
</ItemGroup> </ItemGroup>

View File

@ -7,7 +7,8 @@
} }
}, },
"ConnectionStrings": { "ConnectionStrings": {
"Conn_Admin": "server=127.0.0.1;database=admin;user=zr;pwd=abc" "Conn_Admin": "server=127.0.0.1,1433;database=admin;user=admin;pwd=abc",
"ConnDynamic": "server=127.0.0.1,1433;uid=dev_test;Password=%54Gz@cn;database={database}"
}, },
"urls": "http://localhost:8888", "urls": "http://localhost:8888",
"sysConfig": { "sysConfig": {

View File

@ -43,9 +43,9 @@ namespace ZR.CodeGenerator
_option.ModelsNamespace = baseNamespace + "ZR.Model"; _option.ModelsNamespace = baseNamespace + "ZR.Model";
//_option.IRepositoriesNamespace = baseNamespace + ".IRepositorie"; //_option.IRepositoriesNamespace = baseNamespace + ".IRepositorie";
_option.RepositoriesNamespace = baseNamespace + "ZR.Repository"; _option.RepositoriesNamespace = baseNamespace + "ZR.Repository";
//_option.IServicsNamespace = baseNamespace + ".IService"; _option.IServicsNamespace = baseNamespace + "ZR.Service";
_option.ServicesNamespace = baseNamespace + "ZR.Service"; _option.ServicesNamespace = baseNamespace + "ZR.Service";
_option.ApiControllerNamespace = baseNamespace + "Api"; _option.ApiControllerNamespace = baseNamespace + "ZR.Admin.WebApi";
_option.ReplaceTableNameStr = replaceTableNameStr; _option.ReplaceTableNameStr = replaceTableNameStr;
//_option.TableList = listTable; //_option.TableList = listTable;
@ -88,6 +88,7 @@ namespace ZR.CodeGenerator
var modelsNamespace = _option.ModelsNamespace; var modelsNamespace = _option.ModelsNamespace;
var modelTypeName = GetModelName(tableInfo.Name); ;//表名 var modelTypeName = GetModelName(tableInfo.Name); ;//表名
var modelTypeDesc = tableInfo.Description;//表描述 var modelTypeDesc = tableInfo.Description;//表描述
var primaryKey = "id";//主键
string keyTypeName = "string";//主键数据类型 string keyTypeName = "string";//主键数据类型
string modelcontent = "";//数据库模型字段 string modelcontent = "";//数据库模型字段
@ -111,6 +112,7 @@ namespace ZR.CodeGenerator
modelcontent += " /// </summary>\n"; modelcontent += " /// </summary>\n";
if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey) if (dbFieldInfo.IsIdentity || dbFieldInfo.IsPrimarykey)
{ {
primaryKey = columnName;
modelcontent += $" [SqlSugar.SugarColumn(IsPrimaryKey = {dbFieldInfo.IsPrimarykey.ToString().ToLower()}, IsIdentity = {dbFieldInfo.IsIdentity.ToString().ToLower()})]\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"; modelcontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r";
@ -121,39 +123,43 @@ namespace ZR.CodeGenerator
//} //}
//outputDtocontent += string.Format(" public {0} {1}", dbFieldInfo.DataType, columnName); //outputDtocontent += string.Format(" public {0} {1}", dbFieldInfo.DataType, columnName);
//outputDtocontent += " { get; set; }\n\r"; //outputDtocontent += " { get; set; }\n\r";
//if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint") if (dbFieldInfo.DataType == "bool" || dbFieldInfo.DataType == "tinyint")
//{ {
// vueViewListContent += string.Format(" <el-table-column prop=\"{0}\" label=\"{1}\" sortable=\"custom\" width=\"120\" >\n", columnName, dbFieldInfo.ColumnDescription); vueViewListContent += string.Format(" <el-table-column prop=\"{0}\" label=\"{1}\" sortable=\"custom\" width=\"120\" >\n", columnName, dbFieldInfo.ColumnDescription);
// vueViewListContent += " <template slot-scope=\"scope\">\n"; vueViewListContent += " <template slot-scope=\"scope\">\n";
// vueViewListContent += string.Format(" <el-tag :type=\"scope.row.{0} === true ? 'success' : 'info'\" disable-transitions >", columnName); vueViewListContent += string.Format(" <el-tag :type=\"scope.row.{0} === true ? 'success' : 'info'\" disable-transitions >", columnName);
// vueViewListContent += "{{ "; vueViewListContent += "{{ ";
// vueViewListContent += string.Format("scope.row.{0}===true?'启用':'禁用' ", columnName); vueViewListContent += string.Format("scope.row.{0}===true?'启用':'禁用' ", columnName);
// vueViewListContent += "}}</el-tag>\n"; vueViewListContent += "}}</el-tag>\n";
// vueViewListContent += " </template>\n"; vueViewListContent += " </template>\n";
// vueViewListContent += " </el-table-column>\n"; vueViewListContent += " </el-table-column>\n";
// vueViewFromContent += string.Format(" <el-form-item label=\"{0}\" :label-width=\"formLabelWidth\" prop=\"{1}\">", dbFieldInfo.ColumnDescription, columnName); vueViewFromContent += string.Format(" <el-form-item label=\"{0}\" :label-width=\"labelWidth\" prop=\"{1}\">", dbFieldInfo.ColumnDescription, columnName);
// vueViewFromContent += string.Format(" <el-radio-group v-model=\"editFrom.{0}\">\n", columnName); vueViewFromContent += string.Format(" <el-radio-group v-model=\"editFrom.{0}\">\n", columnName);
// vueViewFromContent += " <el-radio label=\"true\">是</el-radio>\n"; vueViewFromContent += " <el-radio label=\"true\">是</el-radio>\n";
// vueViewFromContent += " <el-radio label=\"false\">否</el-radio>\n"; vueViewFromContent += " <el-radio label=\"false\">否</el-radio>\n";
// vueViewFromContent += " </el-radio-group>\n"; vueViewFromContent += " </el-radio-group>\n";
// vueViewFromContent += " </el-form-item>\n"; vueViewFromContent += " </el-form-item>\n";
// vueViewEditFromContent += string.Format(" {0}: 'true',\n", columnName); vueViewEditFromContent += string.Format(" {0}: 'true',\n", columnName);
// vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.ResData.{0}+''\n", columnName); vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.data.{0}+''\n", columnName);
//} }
//else else
//{ {
// vueViewListContent += string.Format(" <el-table-column prop=\"{0}\" label=\"{1}\" sortable=\"custom\" width=\"120\" />\n", columnName, dbFieldInfo.ColumnDescription); //table-column
vueViewListContent += $" <el-table-column prop=\"{FirstLowerCase(columnName)}\" label=\"{GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" />\n";
// vueViewFromContent += string.Format(" <el-form-item label=\"{0}\" :label-width=\"formLabelWidth\" prop=\"{1}\">\n", dbFieldInfo.ColumnDescription, columnName); //form-item
// vueViewFromContent += string.Format(" <el-input v-model=\"editFrom.{0}\" placeholder=\"请输入{1}\" autocomplete=\"off\" clearable />\n", columnName, dbFieldInfo.ColumnDescription); vueViewFromContent += $" <el-form-item label=\"{ GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" :label-width=\"labelWidth\" prop=\"{FirstLowerCase(columnName)}\">\n";
// vueViewFromContent += " </el-form-item>\n"; vueViewFromContent += $" <el-input v-model=\"form.{FirstLowerCase(columnName)}\" placeholder=\"请输入{GetLabelName(dbFieldInfo.ColumnDescription, columnName)}\" clearable />\n";
// vueViewEditFromContent += string.Format(" {0}: '',\n", columnName); vueViewFromContent += " </el-form-item>\n";
// vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.ResData.{0}\n", columnName); vueViewEditFromContent += string.Format(" {0}: '',\n", columnName);
//} vueViewEditFromBindContent += string.Format(" this.editFrom.{0} = res.ResData.{0}\n", columnName);
}
//vueViewSaveBindContent += string.Format(" '{0}':this.editFrom.{0},\n", columnName); //vueViewSaveBindContent += string.Format(" '{0}':this.editFrom.{0},\n", columnName);
//Rule 规则验证
//if (!dbFieldInfo.IsNullable) //if (!dbFieldInfo.IsNullable)
//{ //{
// vueViewEditFromRuleContent += string.Format(" {0}: [\n", columnName); // vueViewEditFromRuleContent += string.Format(" {0}: [\n", columnName);
@ -169,23 +175,20 @@ namespace ZR.CodeGenerator
InputDtocontent += " /// <summary>\n"; InputDtocontent += " /// <summary>\n";
InputDtocontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription); InputDtocontent += string.Format(" /// 设置或获取{0}\n", dbFieldInfo.ColumnDescription);
InputDtocontent += " /// </summary>\n"; InputDtocontent += " /// </summary>\n";
//if (dbFieldInfo.FieldType == "string")
//{
// InputDtocontent += string.Format(" [MaxLength({0})]\n", dbFieldInfo.FieldMaxLength);
//}
InputDtocontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r"; InputDtocontent += $" public {TableMappingHelper.GetPropertyDatatype(dbFieldInfo.DataType)} {columnName} {{ get; set; }}\n\r";
//} //}
// //
} }
GenerateModels(modelsNamespace, modelTypeName, tableInfo.Name, modelcontent, modelTypeDesc, keyTypeName, ifExsitedCovered); //GenerateModels(modelsNamespace, modelTypeName, tableInfo.Name, modelcontent, modelTypeDesc, keyTypeName, ifExsitedCovered);
GenerateInputDto(modelsNamespace, modelTypeName, modelTypeDesc, InputDtocontent, keyTypeName, ifExsitedCovered); //GenerateInputDto(modelsNamespace, modelTypeName, modelTypeDesc, InputDtocontent, keyTypeName, ifExsitedCovered);
//GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); //GenerateRepository(modelTypeName, modelTypeDesc, tableInfo.Name, keyTypeName, ifExsitedCovered);
//GenerateRepository(modelTypeName, modelTypeDesc, tableInfo.TableName, keyTypeName, ifExsitedCovered);
//GenerateIService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); //GenerateIService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); //GenerateService(modelsNamespace, modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateControllers(modelTypeName, primaryKey, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateIRepository(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered);
//GenerateOutputDto(modelTypeName, modelTypeDesc, outputDtocontent, ifExsitedCovered); //GenerateOutputDto(modelTypeName, modelTypeDesc, outputDtocontent, ifExsitedCovered);
//GenerateControllers(modelTypeName, modelTypeDesc, keyTypeName, ifExsitedCovered); GenerateVueViews(modelTypeName, primaryKey, modelTypeDesc, vueViewListContent, vueViewFromContent, vueViewEditFromContent, vueViewEditFromBindContent, vueViewSaveBindContent, vueViewEditFromRuleContent, ifExsitedCovered);
//GenerateVueViews(modelTypeName, modelTypeDesc, vueViewListContent, vueViewFromContent, vueViewEditFromContent, vueViewEditFromBindContent, vueViewSaveBindContent, vueViewEditFromRuleContent, ifExsitedCovered);
} }
@ -261,6 +264,210 @@ namespace ZR.CodeGenerator
} }
#endregion #endregion
#region Repository
/// <summary>
/// 生成Repository层代码文件
/// </summary>
/// <param name="modelTypeName"></param>
/// <param name="modelTypeDesc"></param>
/// <param name="tableName">表名</param>
/// <param name="keyTypeName"></param>
/// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param>
private static void GenerateRepository(string modelTypeName, string modelTypeDesc, string tableName, string keyTypeName, bool ifExsitedCovered = false)
{
//var path = AppDomain.CurrentDomain.BaseDirectory;
var parentPath = "..";// path.Substring(0, path.LastIndexOf("\\"));
var repositoryPath = parentPath + "\\" + _option.BaseNamespace + "\\" + _option.RepositoriesNamespace;
if (!Directory.Exists(repositoryPath))
{
//repositoryPath = parentPath + "\\" + _option.BaseNamespace + "\\Repositories";
Directory.CreateDirectory(repositoryPath);
}
var fullPath = repositoryPath + "\\" + modelTypeName + "Repository.cs";
if (File.Exists(fullPath) && !ifExsitedCovered)
return;
var content = ReadTemplate("RepositoryTemplate.txt");
content = content.Replace("{ModelsNamespace}", _option.ModelsNamespace)
.Replace("{IRepositoriesNamespace}", _option.IRepositoriesNamespace)
.Replace("{RepositoriesNamespace}", _option.RepositoriesNamespace)
.Replace("{ModelTypeName}", modelTypeName)
.Replace("{TableNameDesc}", modelTypeDesc)
.Replace("{TableName}", tableName)
.Replace("{KeyTypeName}", keyTypeName);
WriteAndSave(fullPath, content);
}
#endregion
#region Service
/// <summary>
/// 生成IService文件
/// </summary>
/// <param name="modelsNamespace"></param>
/// <param name="modelTypeName"></param>
/// <param name="modelTypeDesc"></param>
/// <param name="keyTypeName"></param>
/// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param>
private static void GenerateIService(string modelsNamespace, string modelTypeName, string modelTypeDesc, string keyTypeName, bool ifExsitedCovered = false)
{
//var path = AppDomain.CurrentDomain.BaseDirectory;
//path = path.Substring(0, path.IndexOf("\\bin"));
var parentPath = "..";// path.Substring(0, path.LastIndexOf("\\"));
var iServicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + _option.IServicsNamespace;
if (!Directory.Exists(iServicesPath))
{
iServicesPath = parentPath + "\\" + _option.BaseNamespace + "\\IBusService";
Directory.CreateDirectory(iServicesPath);
}
var fullPath = $"{iServicesPath}\\Business\\IService\\I{modelTypeName}Service.cs";
if (File.Exists(fullPath) && !ifExsitedCovered)
return;
var content = ReadTemplate("IServiceTemplate.txt");
content = content.Replace("{ModelsNamespace}", modelsNamespace)
.Replace("{DtosNamespace}", _option.DtosNamespace)
.Replace("{TableNameDesc}", modelTypeDesc)
.Replace("{IServicsNamespace}", _option.IServicsNamespace)
.Replace("{ModelTypeName}", modelTypeName)
.Replace("{KeyTypeName}", keyTypeName);
WriteAndSave(fullPath, content);
}
/// <summary>
/// 生成Service文件
/// </summary>
/// <param name="modelsNamespace"></param>
/// <param name="modelTypeName"></param>
/// <param name="modelTypeDesc"></param>
/// <param name="keyTypeName"></param>
/// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param>
private static void GenerateService(string modelsNamespace, string modelTypeName, string modelTypeDesc, string keyTypeName, bool ifExsitedCovered = false)
{
//var path = AppDomain.CurrentDomain.BaseDirectory;
//path = path.Substring(0, path.IndexOf("\\bin"));
var parentPath = "..";// path.Substring(0, path.LastIndexOf("\\"));
var servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + _option.ServicesNamespace;
if (!Directory.Exists(servicesPath))
{
servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\Business";
Directory.CreateDirectory(servicesPath);
}
var fullPath = servicesPath + "\\Business\\" + modelTypeName + "Service.cs";
Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !ifExsitedCovered)
return;
var content = ReadTemplate("ServiceTemplate.txt");
content = content
.Replace("{IRepositoriesNamespace}", _option.IRepositoriesNamespace)
.Replace("{DtosNamespace}", _option.DtosNamespace)
.Replace("{IServicsNamespace}", _option.IServicsNamespace)
.Replace("{TableNameDesc}", modelTypeDesc)
.Replace("{ModelsNamespace}", modelsNamespace)
.Replace("{ServicesNamespace}", _option.ServicesNamespace)
.Replace("{ModelTypeName}", modelTypeName)
.Replace("{KeyTypeName}", keyTypeName);
WriteAndSave(fullPath, content);
}
#endregion
#region Controller
/// <summary>
/// 生成控制器ApiControllers文件
/// </summary>
/// <param name="modelTypeName">实体类型名称</param>
/// <param name="primaryKey">主键</param>
/// <param name="modelTypeDesc">实体描述</param>
/// <param name="keyTypeName"></param>
/// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param>
private static void GenerateControllers(string modelTypeName, string primaryKey, string modelTypeDesc, string keyTypeName, bool ifExsitedCovered = false)
{
//var servicesNamespace = _option.DtosNamespace;
//var fileClassName = _option.BaseNamespace.Substring(_option.BaseNamespace.IndexOf('.') + 1);
//var path = AppDomain.CurrentDomain.BaseDirectory;
//path = path.Substring(0, path.IndexOf("\\bin"));
var parentPath = "..";//path.Substring(0, path.LastIndexOf("\\"));
var servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + _option.ApiControllerNamespace;
if (!Directory.Exists(servicesPath))
{
servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\Controllers\\";
Directory.CreateDirectory(servicesPath);
}
var fullPath = servicesPath + "\\Controllers\\business\\" + modelTypeName + "Controller.cs";
Console.WriteLine(fullPath);
if (File.Exists(fullPath) && !ifExsitedCovered)
return;
var content = ReadTemplate("ControllersTemplate.txt");
content = content
//.Replace("{DtosNamespace}", _option.DtosNamespace)
.Replace("<#=ControllerName#>", modelTypeName)
//.Replace("{ModelsNamespace}", _option.ModelsNamespace)
.Replace("<#=FileName#>", modelTypeDesc)
.Replace("<#=ServiceName#>", modelTypeName + "Service")
.Replace("<#=ModelName#>", modelTypeName)
.Replace("{primaryKey}", primaryKey)
.Replace("{KeyTypeName}", keyTypeName);
WriteAndSave(fullPath, content);
}
#endregion
#region Vue页面
/// <summary>
/// 生成Vue页面
/// </summary>
/// <param name="modelTypeName">类名</param>
/// <param name="modelTypeDesc">表/类描述</param>
/// <param name="vueViewListContent"></param>
/// <param name="vueViewFromContent"></param>
/// <param name="vueViewEditFromContent"></param>
/// <param name="vueViewEditFromBindContent"></param>
/// <param name="vueViewSaveBindContent"></param>
/// <param name="vueViewEditFromRuleContent"></param>
/// <param name="ifExsitedCovered">如果目标文件存在是否覆盖。默认为false</param>
private static void GenerateVueViews(string modelTypeName, string primaryKey, string modelTypeDesc, string vueViewListContent, string vueViewFromContent, string vueViewEditFromContent, string vueViewEditFromBindContent, string vueViewSaveBindContent, string vueViewEditFromRuleContent, bool ifExsitedCovered = false)
{
var servicesNamespace = _option.DtosNamespace;
var fileClassName = _option.BaseNamespace.Substring(_option.BaseNamespace.IndexOf('.') + 1);
var path = AppDomain.CurrentDomain.BaseDirectory;
//path = path.Substring(0, path.IndexOf("\\bin"));
var parentPath = path.Substring(0, path.LastIndexOf("\\"));
var servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\" + servicesNamespace;
if (!Directory.Exists(servicesPath))
{
servicesPath = parentPath + "\\" + _option.BaseNamespace + "\\vue\\" + modelTypeName.ToLower();
Directory.CreateDirectory(servicesPath);
}
var fullPath = servicesPath + "\\" + "index.vue";
if (File.Exists(fullPath) && !ifExsitedCovered)
return;
var content = ReadTemplate("VueTemplate.txt");
content = content
.Replace("{BaseNamespace}", fileClassName.ToLower())
.Replace("{fileClassName}", modelTypeName.ToLower())
.Replace("{ModelTypeNameToLower}", modelTypeName.ToLower())
.Replace("{VueViewListContent}", vueViewListContent)
.Replace("{VueViewFromContent}", vueViewFromContent)
.Replace("{ModelTypeName}", modelTypeName)
.Replace("{VueViewEditFromContent}", vueViewEditFromContent)
.Replace("{VueViewEditFromBindContent}", vueViewEditFromBindContent)
.Replace("{VueViewSaveBindContent}", vueViewSaveBindContent)
.Replace("{primaryKey}", primaryKey)
.Replace("{VueViewEditFromRuleContent}", vueViewEditFromRuleContent);
WriteAndSave(fullPath, content);
fullPath = servicesPath + "\\" + modelTypeName.ToLower() + ".js";
if (File.Exists(fullPath) && !ifExsitedCovered)
return;
content = ReadTemplate("VueJsTemplate.txt");
content = content
.Replace("{ModelTypeName}", modelTypeName)
.Replace("{ModelTypeDesc}", modelTypeDesc)
.Replace("{fileClassName}", fileClassName);
WriteAndSave(fullPath, content);
}
#endregion
#region #region
private static string GetModelName(string modelTypeName) private static string GetModelName(string modelTypeName)
@ -273,7 +480,19 @@ namespace ZR.CodeGenerator
modelTypeName = modelTypeName.Substring(0, 1).ToUpper() + modelTypeName.Substring(1); modelTypeName = modelTypeName.Substring(0, 1).ToUpper() + modelTypeName.Substring(1);
return modelTypeName; return modelTypeName;
} }
private static string FirstLowerCase(string str)
{
if (string.IsNullOrEmpty(str))
{
return str;
}
str = str.Substring(0, 1).ToLower() + str.Substring(1);
return str;
}
private static string GetLabelName(string columnDescription, string columnName)
{
return string.IsNullOrEmpty(columnDescription) ? columnName : columnDescription;
}
/// <summary> /// <summary>
/// 从代码模板中读取内容 /// 从代码模板中读取内容
/// </summary> /// </summary>
@ -309,17 +528,24 @@ namespace ZR.CodeGenerator
/// <param name="content"></param> /// <param name="content"></param>
private static void WriteAndSave(string fileName, string content) private static void WriteAndSave(string fileName, string content)
{ {
//实例化一个文件流--->与写入文件相关联 try
using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write); {
//实例化一个StreamWriter-->与fs相关联 //实例化一个文件流--->与写入文件相关联
using var sw = new StreamWriter(fs); using var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
//开始写入 //实例化一个StreamWriter-->与fs相关联
sw.Write(content); using var sw = new StreamWriter(fs);
//清空缓冲区 //开始写入
sw.Flush(); sw.Write(content);
//关闭流 //清空缓冲区
sw.Close(); sw.Flush();
fs.Close(); //关闭流
sw.Close();
fs.Close();
}
catch (Exception ex)
{
Console.WriteLine("写入文件出错了:" + ex.Message);
}
} }
#endregion #endregion

View File

@ -10,13 +10,23 @@ namespace ZR.CodeGenerator
{ {
public class DbProvider public class DbProvider
{ {
protected static SqlSugarScope CodeDb;
public SqlSugarClient GetSugarDbContext(string dbName) /// <summary>
/// 获取动态连接字符串
/// </summary>
/// <param name="dbName">数据库名</param>
/// <returns></returns>
public SqlSugarScope GetSugarDbContext(string dbName = "")
{ {
string connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.Conn).Replace("{DbName}", dbName); string connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.Conn).Replace("{database}", dbName);
int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.CodeGenDbType, 0); int dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.CodeGenDbType, 0);
if (string.IsNullOrEmpty(dbName))
return new SqlSugarClient(new List<ConnectionConfig>() {
connStr = ConfigUtils.Instance.GetConnectionStrings(OptionsSetting.ConnAdmin);
dbType = ConfigUtils.Instance.GetAppConfig(OptionsSetting.DbType, 0);
}
var db = new SqlSugarScope(new List<ConnectionConfig>()
{ {
new ConnectionConfig(){ new ConnectionConfig(){
ConnectionString = connStr, ConnectionString = connStr,
@ -25,6 +35,9 @@ namespace ZR.CodeGenerator
InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息 InitKeyType = InitKeyType.Attribute,//从特性读取主键和自增列信息
}, },
}); });
CodeDb = db;
return db;
} }
} }
} }

View File

@ -1,16 +1,12 @@
using Infrastructure; using SqlSugar;
using SqlSugar;
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; using ZR.Model;
using ZR.Model.CodeGenerator; using ZR.Model.CodeGenerator;
namespace ZR.CodeGenerator.Service namespace ZR.CodeGenerator.Service
{ {
public class CodeGeneraterService: DbProvider public class CodeGeneraterService : DbProvider
{ {
/// <summary> /// <summary>
/// 获取所有数据库名 /// 获取所有数据库名
@ -18,21 +14,15 @@ namespace ZR.CodeGenerator.Service
/// <returns></returns> /// <returns></returns>
public List<DataBaseInfo> GetAllDataBases() public List<DataBaseInfo> GetAllDataBases()
{ {
var dbType = ConfigUtils.Instance.GetConfig("CodeGenDbType"); List<DataBaseInfo> list = new();
List<DataBaseInfo> list = new List<DataBaseInfo>();
if (dbType == "1") var db = GetSugarDbContext();
var templist = db.DbMaintenance.GetDataBaseList(db.ScopedContext);
templist.ForEach(item =>
{ {
var db = GetSugarDbContext("ZrAdmin"); list.Add(new DataBaseInfo() { DbName = item });
var templist = db.DbMaintenance.GetDataBaseList(db); });
templist.ForEach(item =>
{
list.Add(new DataBaseInfo() { DbName = item });
});
}
else if (dbType == "0")
{
// list = mssqlExtractor.GetAllDataBases();
}
return list; return list;
} }
@ -43,7 +33,7 @@ namespace ZR.CodeGenerator.Service
/// <param name="tableName"></param> /// <param name="tableName"></param>
/// <param name="pager"></param> /// <param name="pager"></param>
/// <returns></returns> /// <returns></returns>
public List<SqlSugar.DbTableInfo> GetAllTables(string dbName, string tableName, PagerInfo pager) public List<DbTableInfo> GetAllTables(string dbName, string tableName, PagerInfo pager)
{ {
var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true); var tableList = GetSugarDbContext(dbName).DbMaintenance.GetTableInfoList(true);
if (!string.IsNullOrEmpty(tableName)) if (!string.IsNullOrEmpty(tableName))
@ -62,7 +52,7 @@ namespace ZR.CodeGenerator.Service
/// <returns></returns> /// <returns></returns>
public List<DbColumnInfo> GetColumnInfo(string dbName, string tableName) public List<DbColumnInfo> GetColumnInfo(string dbName, string tableName)
{ {
return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true); return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true);
} }
} }

View File

@ -1,75 +0,0 @@
using Infrastructure.Attribute;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model;
using ZR.Model.CodeGenerator;
namespace ZR.Repository.System
{
[AppService(ServiceLifetime = LifeTime.Transient)]
public class CodeGeneratorRepository : BaseRepository
{
///// <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="tableName"></param>
///// <returns></returns>
//public List<SqlSugar.DbColumnInfo> GetColumnInfo(string dbName, string tableName)
//{
// return GetSugarDbContext(dbName).DbMaintenance.GetColumnInfosByTableName(tableName, true);
//}
/// <summary>
/// 获取当前数据库表名
/// </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";
// return Db.SqlQueryable<DbTableInfo>(sql).WhereIF(tabList.Length > 0, x => tabList.Contains(x.TableName)).ToList();
//}
}
}

View File

@ -1,99 +0,0 @@
using Infrastructure;
using Infrastructure.Attribute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model;
using ZR.Model.CodeGenerator;
using ZR.Repository.System;
using ZR.Service.IService;
namespace ZR.Service.System
{
/// <summary>
///
/// </summary>
//[AppService(ServiceType = typeof(ICodeGeneratorService), ServiceLifetime = LifeTime.Transient)]
public class CodeGeneratorService //: ICodeGeneratorService
{
//public CodeGeneratorRepository CodeGeneratorRepository;
//public CodeGeneratorService(CodeGeneratorRepository codeGeneratorRepository)
//{
// CodeGeneratorRepository = codeGeneratorRepository;
//}
///// <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>
///// <returns></returns>
//public List<DataBaseInfo> GetAllDataBases()
//{
// var dbType = ConfigUtils.Instance.GetConfig("CodeGenDbType");
// List<DataBaseInfo> list = new List<DataBaseInfo>();
// if (dbType == "1")
// {
// list = CodeGeneratorRepository.GetAllDb();
// }
// else if (dbType == "0")
// {
// // list = mssqlExtractor.GetAllDataBases();
// }
// return list;
//}
//public List<DbTableInfo> GetAllTables(string tableStrs)
//{
// string[] tabList = tableStrs.Split(",");
// return CodeGeneratorRepository.GetAllTables(tabList);
//}
/// <summary>
/// 获取列信息
/// </summary>
/// <param name="dbName"></param>
/// <param name="tableName"></param>
/// <returns></returns>
//public List<SqlSugar.DbColumnInfo> GetColumnInfo(string dbName, string tableName)
//{
// return CodeGeneratorRepository.GetColumnInfo(dbName, tableName);
//}
//public List<SqlSugar.DbTableInfo> GetTablesWithPage(string tablename, string dbName, PagerInfo pager)
//{
// var dbType = ConfigUtils.Instance.GetConfig("CodeGenDbType");
// List<SqlSugar.DbTableInfo> list = new List<SqlSugar.DbTableInfo>();
// if (dbType == "1")
// {
// list = CodeGeneratorRepository.GetAllTables(dbName, tablename, pager);
// }
// else if (dbType == "0")
// {
// //list = mysqlExtractor.GetAllTables(this.dbName, tablename, fieldNameToSort, isDescending, info);
// }
// return list;
//}
}
}

View File

@ -9,4 +9,8 @@
<ProjectReference Include="..\ZR.Repository\ZR.Repository.csproj" /> <ProjectReference Include="..\ZR.Repository\ZR.Repository.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="Business\IService\" />
</ItemGroup>
</Project> </Project>

View File

@ -32,30 +32,26 @@
<el-card> <el-card>
<div class="list-btn-container"> <div class="list-btn-container">
<el-form ref="codeform" :inline="true" :rules="rules" :model="codeform" class="demo-form-inline" size="small"> <el-form ref="codeform" :inline="true" :rules="rules" :model="codeform" class="demo-form-inline" size="small">
<el-form-item label="数据库"> <el-form-item label="数据库" prop="dbName">
<el-tooltip class="item" effect="dark" content="默认为系统访问数据库" placement="top"> <el-select v-model="codeform.dbName" clearable placeholder="请选择" @change="handleShowTable">
<el-select v-model="searchform.DbName" clearable placeholder="请选择" @change="handleShowTable"> <el-option v-for="item in selectedDataBase" :key="item.Id" :label="item.dbName" :value="item.dbName" />
<el-option v-for="item in selectedDataBase" :key="item.Id" :label="item.dbName" :value="item.dbName" /> </el-select>
</el-select>
</el-tooltip>
</el-form-item> </el-form-item>
<el-form-item label="表名"> <el-form-item label="表名">
<el-input v-model="searchform.tableName" clearable placeholder="输入要查询的表名" /> <el-input v-model="searchform.tableName" clearable placeholder="输入要查询的表名" />
</el-form-item> </el-form-item>
<el-form-item> <!-- <el-form-item label="项目命名空间:" prop="baseSpace">
<el-button type="primary" @click="handleSearch()">查询</el-button>
</el-form-item>
<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="多个前缀用“;”隔开" /> <el-input v-model="codeform.replaceTableNameStr" clearable width="300" placeholder="多个前缀用“;”隔开" />
</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" icon="iconfont icon-code" @click="handleGenerate()">生成代码</el-button> --> <!-- <el-button type="primary" icon="iconfont icon-code" @click="handleGenerate()">生成代码</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>
@ -105,7 +101,7 @@ export default {
DbType: "", DbType: "",
}, },
searchform: { searchform: {
DbName: "", dbName: "",
tableName: "", tableName: "",
}, },
codeform: { codeform: {
@ -122,6 +118,9 @@ export default {
// trigger: "blur", // trigger: "blur",
// }, // },
// ], // ],
dbName: [
{ required: true, message: "请选择数据库名称", trigger: "blur" },
],
replaceTableNameStr: [ replaceTableNameStr: [
{ min: 0, max: 50, message: "长度小于50个字符", trigger: "blur" }, { min: 0, max: 50, message: "长度小于50个字符", trigger: "blur" },
], ],
@ -166,15 +165,13 @@ export default {
* 加载页面table数据 * 加载页面table数据
*/ */
loadTableData: function () { loadTableData: function () {
if (this.searchform.dataBaseName !== "") { if (this.codeform.dataBaseName !== "") {
this.tableloading = true; this.tableloading = true;
var seachdata = { var seachdata = {
pageNum: this.pagination.pageNum, pageNum: this.pagination.pageNum,
PageSize: this.pagination.pagesize, PageSize: this.pagination.pagesize,
tableName: this.searchform.tableName, tableName: this.codeform.tableName,
dbName: this.searchform.DbName, dbName: this.codeform.dbName,
// Order: this.sortableData.order,
// Sort: this.sortableData.sort,
}; };
codeGetTableList(seachdata).then((res) => { codeGetTableList(seachdata).then((res) => {
this.tableData = res.data.result; this.tableData = res.data.result;
@ -187,9 +184,15 @@ export default {
* 点击查询 * 点击查询
*/ */
handleSearch: function () { handleSearch: function () {
this.tableloading = true; this.$refs["codeform"].validate((valid) => {
this.pagination.pageNum = 1; if (valid) {
this.loadTableData(); this.tableloading = true;
this.pagination.pageNum = 1;
this.loadTableData();
}else{
return false;
}
});
}, },
handleShowTable: function () { handleShowTable: function () {
this.pagination.pageNum = 1; this.pagination.pageNum = 1;
@ -231,7 +234,7 @@ export default {
const pageLoading = Loading.service(loadop); const pageLoading = Loading.service(loadop);
var seachdata = { var seachdata = {
dbName: this.searchform.DbName, dbName: this.codeform.dbName,
tables: row.name, // this.currentSelected.toString(), tables: row.name, // this.currentSelected.toString(),
baseSpace: this.codeform.baseSpace, baseSpace: this.codeform.baseSpace,
replaceTableNameStr: this.codeform.replaceTableNameStr, replaceTableNameStr: this.codeform.replaceTableNameStr,