YiShaAdmin代码生成器:基于数据库表自动生成CRUD代码

YiShaAdmin代码生成器:基于数据库表自动生成CRUD代码

【免费下载链接】YiShaAdmin 基于 .NET Core MVC 的权限管理系统,代码易读易懂、界面简洁美观 【免费下载链接】YiShaAdmin 项目地址: https://gitcode.com/GitHub_Trending/yi/YiShaAdmin

一、为什么需要代码生成器?

你还在手动编写重复的CRUD代码吗?还在为实体类、服务层、控制器的模板代码浪费时间吗?YiShaAdmin的代码生成器(Code Generator)可帮你从繁琐的重复劳动中解放出来,只需简单配置,即可一键生成完整的业务模块代码,包括实体类、数据访问层、业务逻辑层、API接口和前端页面。

读完本文你将获得:

  • 了解YiShaAdmin代码生成器的核心原理
  • 掌握从数据库表结构到完整业务模块的自动生成流程
  • 学会自定义生成模板以满足特定业务需求

二、代码生成器核心架构

YiShaAdmin代码生成器位于YiSha.Util/YiSha.CodeGenerator/目录下,主要由表结构映射工具和模板生成引擎两部分组成。

2.1 表结构映射工具

TableMappingHelper.cs负责数据库表结构到C#实体的映射,核心功能包括:

  1. 类名生成:将数据库表名(如sys_menu)转换为实体类名(MenuEntity)
public static string GetClassNamePrefix(string tableName)
{
    string[] arr = tableName.Split('_');
    StringBuilder sb = new StringBuilder();
    for (int i = 1; i < arr.Length; i++)
    {
        sb.Append(arr[i][0].ToString().ToUpper() + arr[i].Substring(1));
    }
    return sb.ToString();
}
  1. 数据类型映射:将SQL数据类型转换为C#可空类型
public static string GetPropertyDatatype(string sDatatype)
{
    switch (sDatatype.ToLower())
    {
        case "int":
        case "number":
            return "int?";
        case "bigint":
            return "long?";
        case "datetime":
            return "DateTime?";
        // 更多类型映射...
    }
}

2.2 模板生成引擎

SingleTableTemplate.cs是模板生成的核心,支持生成以下文件类型:

  • 实体类(Entity)
  • 数据访问层(Repository)
  • 业务逻辑层(Service/Business)
  • API控制器(Controller)
  • 前端页面(Views)

生成流程如图所示: mermaid

三、快速使用指南

3.1 环境准备

  1. 克隆项目仓库:
git clone https://gitcode.com/GitHub_Trending/yi/YiShaAdmin.git
  1. 准备数据库表结构,推荐包含以下基础字段:
    • id: 主键
    • create_time: 创建时间
    • update_time: 更新时间
    • is_delete: 删除标记

3.2 生成配置

代码生成器通过BaseConfigModel管理生成配置,核心配置项包括:

public class BaseConfigModel
{
    public string TableName { get; set; } // 数据库表名
    public FileConfigModel FileConfig { get; set; } // 文件生成配置
    public OutputConfigModel OutputConfig { get; set; } // 输出路径配置
    public PageIndexModel PageIndex { get; set; } // 列表页配置
    public PageFormModel PageForm { get; set; } // 表单页配置
}

配置示例:

var config = new BaseConfigModel();
config.TableName = "sys_user";
config.FileConfig.ClassPrefix = "User";
config.OutputConfig.OutputModule = "SystemManage";
config.PageIndex.ColumnList = new List<string> { "UserName", "NickName", "Phone" };

3.3 生成代码

调用SingleTableTemplate.cs的生成方法:

var template = new SingleTableTemplate();
var config = template.GetBaseConfig(path, "admin", "sys_user", "用户信息表", new List<string>{"UserName","NickName"});

// 生成实体类
string entityCode = template.BuildEntity(config, dt);
// 生成服务层
string serviceCode = template.BuildService(config, dt);
// 生成控制器
string controllerCode = template.BuildController(config);

四、生成代码结构解析

以"用户管理"模块为例,生成的代码结构如下:

4.1 实体层(Entity)

YiSha.Entity/SystemManage/UserEntity.cs

[Table("sys_user")]
public class UserEntity : BaseEntity
{
    /// <summary>
    /// 用户名
    /// </summary>
    public string UserName { get; set; }
    
    /// <summary>
    /// 昵称
    /// </summary>
    public string NickName { get; set; }
    
    /// <summary>
    /// 手机号码
    /// </summary>
    public string Phone { get; set; }
}

4.2 服务层(Service)

YiSha.Service/SystemManage/UserService.cs

public class UserService : RepositoryFactory
{
    public async Task<List<UserEntity>> GetList(UserListParam param)
    {
        var expression = LinqExtensions.True<UserEntity>();
        if (!param.UserName.IsEmpty())
        {
            expression = expression.And(t => t.UserName.Contains(param.UserName));
        }
        return await this.BaseRepository().FindList(expression);
    }
    
    public async Task SaveForm(UserEntity entity)
    {
        if (entity.Id.IsNullOrZero())
        {
            entity.CreateTime = DateTime.Now;
            await this.BaseRepository().Insert(entity);
        }
        else
        {
            entity.UpdateTime = DateTime.Now;
            await this.BaseRepository().Update(entity);
        }
    }
}

4.3 控制器(Controller)

YiSha.Admin.Web/Areas/SystemManage/Controllers/UserController.cs

[Area("SystemManage")]
public class UserController : BaseController
{
    private UserBusiness userBusiness = new UserBusiness();
    
    [HttpGet]
    public async Task<ActionResult> GetPageList(UserListParam param, Pagination pagination)
    {
        TData<List<UserEntity>> obj = await userBusiness.GetPageList(param, pagination);
        return Json(obj);
    }
    
    [HttpPost]
    public async Task<ActionResult> SaveForm(UserEntity entity)
    {
        TData<string> obj = await userBusiness.SaveForm(entity);
        return Json(obj);
    }
}

4.4 前端页面

生成的列表页如图所示: 用户管理列表页

列表页代码位于YiSha.Admin.Web/Areas/SystemManage/Views/User/UserIndex.cshtml,主要包含:

  • 搜索区域
  • 数据表格
  • 操作按钮

五、自定义模板

5.1 修改模板文件

代码生成器支持通过修改模板文件自定义生成代码风格,模板文件位于YiSha.Util/YiSha.CodeGenerator/Template/目录。

例如,修改实体类模板:

// 原模板
sb.AppendLine("    [Table(\"" + baseConfigModel.TableName + "\")]");
sb.AppendLine("    public class " + baseConfigModel.FileConfig.EntityName + " : BaseEntity");

// 自定义后
sb.AppendLine("    [Table(\"" + baseConfigModel.TableName + "\")]");
sb.AppendLine("    [Description(\"" + baseConfigModel.FileConfig.ClassDescription + "\")]");
sb.AppendLine("    public class " + baseConfigModel.FileConfig.EntityName + " : BaseEntity");

5.2 扩展数据类型映射

TableMappingHelper.cs中添加新的数据类型映射:

case "json":
case "jsonb":
    sTempDatatype = "JObject";
    break;

六、总结与展望

YiShaAdmin代码生成器通过自动化模板生成,大幅提升了开发效率,使开发者能够专注于核心业务逻辑。目前支持单表生成,未来计划增加:

  • 多表关联生成
  • 树形结构数据生成
  • 导入导出功能自动生成

官方文档:Document/_readme.txt 社区教程:README.md 源码地址:YiSha.Util/YiSha.CodeGenerator/

通过代码生成器,一个标准的业务模块开发时间从原来的2小时缩短到5分钟,让我们把更多时间用在创造性工作上!

【免费下载链接】YiShaAdmin 基于 .NET Core MVC 的权限管理系统,代码易读易懂、界面简洁美观 【免费下载链接】YiShaAdmin 项目地址: https://gitcode.com/GitHub_Trending/yi/YiShaAdmin

创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值