Net 6.0中实现自动生成代码

1、前言

生成代码NuGet包:XmSoft.CodeGenerator

该包将会自动生成代码,如:实体,仓储,服务,控制器及校验等文件。

控制器包含CRUD接口:创建,修改,删除,详情,列表。

参考:ORM框架采用SqlSugar框架生成

2、示例

//创建控制台应用 输出项目名称自定义
dotnet new console -o XmSoft.AutoCode 
//引入NuGet
dotnet add package XmSoft.CodeGenerator
//appsettings.json 配置代码命名空间及输出位置
//比如:

{
  "CodeHelperOptions": {
    "ConnectConnectionString": "Server=127.0.0.1;Uid=sa;Pwd=xxxxxxx;Database=test;Port=3306;Charset=utf8;",
    "ProviderName": "MySql.Data.MySqlClient",
    "NameSpace": {
      "ModelsNamespace": "XmSoft.Domain.Models",
      "DomainName": "XmSoft.Domain",
      "DtoNamespace":"XmSoft.ViewModels.Dto",
      "ApiControllerNamespace": "XmSoft.Api.Application",
      "InterfaceName": "XmSoft",
      "ServicesNamespace": "XmSoft.Service",
      "RepositoriesNamespace": "XmSoft.Repository",
      "ValidatorNamespace": "XmSoft.Validation"
    },
    "CodePath": {
      "ModelsPath": "XmSoft.Domain/Models/",
      "DtoPath": "XmSoft.ViewModels/Dto/",
      "IRepositoriesPath": "XmSoft.IRepository/",
      "IServicesPath": "XmSoft.IService/",
      "RepositoriesPath": "XmSoft.Repository/",
      "ServicesPath": "XmSoft.Service/",
      "ControllerPath": "XmSoft.Api/Application/",
      "ValidatorPath": "XmSoft.Validation/"
    }
  }
}
//Utility.cs 输入表名,多个用逗号隔开

public static class Utility
{
    public static string[] WriteTables()
    {
        Console.WriteLine("------------请输入数据表名称,多个用逗号隔开------------");
        var strRead = Console.ReadLine();
        var tables = strRead?.Split(',');
        if (string.IsNullOrEmpty(strRead) || tables == null || tables.Length == 0)
        {
            WriteTables();
        }

        return tables ?? Array.Empty();
    }
}
//Program.cs 

Console.WriteLine("自动生成代码");
var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();
var options = configuration.GetSection(nameof(CodeHelperOptions)).Get();
var path = Directory.GetCurrentDirectory();


var filterA= @"XmSoft.AutoCodebinDebug
et6.0"; //XmSoft.AutoCode 修改创建的项目名
var filterB = @"XmSoft.AutoCodebinRelease
et6.0";

path = path.Replace(filterA, "");
path = path.Replace(filterB, "");

Console.WriteLine(#34;{path}");

options.CodePath.ValidatorPath = Path.Combine(path, @options.CodePath.ValidatorPath);
options.CodePath.ControllerPath = Path.Combine(path, @options.CodePath.ControllerPath);
options.CodePath.ModelsPath = Path.Combine(path, @options.CodePath.ModelsPath);
options.CodePath.IRepositoriesPath = Path.Combine(path, @options.CodePath.IRepositoriesPath);
options.CodePath.IServicesPath = Path.Combine(path, @options.CodePath.IServicesPath);
options.CodePath.RepositoriesPath = Path.Combine(path, @options.CodePath.RepositoriesPath);
options.CodePath.ServicesPath = Path.Combine(path, @options.CodePath.ServicesPath);
options.CodePath.DtoPath = Path.Combine(path, @options.CodePath.DtoPath);

var tables = Utility.WriteTables();
options.Tables = tables;
Console.WriteLine("------------是否确定执行(Y/N)------------");
var command = Console.ReadLine();
if (!string.IsNullOrEmpty(command) && command.ToLower() == "y")
{
    var helper = new CodeGeneratorHelper(options);
    helper.Run();
    Console.WriteLine("------------完成------------");
}

Console.ReadKey();

3、执行

z_test表sql语句

DROP TABLE IF EXISTS `z_test`;
CREATE TABLE `z_test`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `business_id` bigint(20) NULL DEFAULT NULL COMMENT '业务id',
  `title` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '标题',
  `content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '内容',
  `picture` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT '图片',
  `status` int(11) NULL DEFAULT NULL COMMENT '状态 0 正常 1 关闭',
  `remark` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '备注说明',
  `sort` int(11) NULL DEFAULT NULL COMMENT '排序',
  `create_time` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '创建Id',
  `update_time` datetime(0) NULL DEFAULT NULL COMMENT '更新时间',
  `update_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '更新Id',
  `delFlag` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT '是否删除 1 是,0 否',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '测试表' ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

补充说明:表必须有个主键key

执行

//生成实体
/// 
/// 测试表
/// 
[SugarTable("z_test")]
public partial class Test : BaseBusinessEntity
{
     /// 
  /// 标题
  /// 
 [SugarColumn(ColumnName = "title")]
  public string Title { get; set; }
     /// 
  /// 内容
  /// 
 [SugarColumn(ColumnName = "content")]
  public string Content { get; set; }
     /// 
  /// 图片
  /// 
 [SugarColumn(ColumnName = "picture")]
  public string Picture { get; set; }
     /// 
  /// 状态 0 正常 1 关闭
  /// 
 [SugarColumn(ColumnName = "status")]
  public int? Status { get; set; }
     /// 
  /// 备注说明
  /// 
 [SugarColumn(ColumnName = "remark")]
  public string Remark { get; set; }
     /// 
  /// 排序
  /// 
 [SugarColumn(ColumnName = "sort")]
  public int? Sort { get; set; }
  }
  
  说明:自定义 BaseBusinessEntity或BaseEntity 自定义,这里的主键名id ,业务id
  
  /// 
/// 
/// 
/// 
public abstract class BaseBusinessEntity : BaseEntity
{
    /// 
    /// 业务Id
    /// 
    [SugarColumn(ColumnName = "business_id")]
    public long? BusinessId { get; set; }
}

public abstract class BaseEntity 
{
    [SugarColumn(IsPrimaryKey = true, IsIdentity = true, ColumnName = "id")]
    public T Id { get; set; }

    /// 
    /// 0未删除 1回收站 2已删除
    /// 
    [SugarColumn(ColumnName = "delFlag")]
    [JsonIgnore]
    public string DelFlag { get; set; }

    /// 
    /// 创建时间
    /// 
    [SugarColumn(ColumnName = "create_time")]
    // [Column("create_time")]
    //[JsonIgnore]
    public DateTime? CreateTime { get; set; }

    /// 
    /// 创建Id
    /// 
    [SugarColumn(ColumnName = "create_by")]
    //[Column("create_id")]
    [JsonIgnore]
    public string Create_By { get; set; }
    /// 
    /// 修改时间
    /// 
    [SugarColumn(ColumnName = "update_time")]
    //[Column("update_time")]
    [JsonIgnore]
    public DateTime? UpdateTime { get; set; }

    /// 
    /// 修改者ID
    /// 
    [SugarColumn(ColumnName = "update_by")]
    //[Column("update_id")]
    [JsonIgnore]
    public string Update_By { get; set; }


    public void Create()
    {
        //Create_By = (userId?.ToString()) ?? Create_By;
        //BusinessId = businessId ?? BusinessId;
        CreateTime = DateTime.Now;
        DelFlag = "0";
    }

    public void Update()
    {
        UpdateTime = DateTime.Now;
    }

}
//生成仓储 EFRepository 引用XmSoft.Core.SqlSugar.Repository
public sealed class TestRepository :EFRepository,ITestRepository
{
  public readonly ISqlSugarClient Context;

  public TestRepository(ISqlSugarClient context) : base(context)
 {
     Context = context;

 }

 public ISugarQueryable SugarQueryable()
 {
     return Context.Queryable();
 }

}
//生成服务 引用XmSoft.Core.SqlSugar.Service
public class TestService : BaseService,ITestService
{
  public TestService(ITestRepository _repository):base(_repository)
  {

  }  

  public async override Task> Create(Test entity, dynamic user)
  {
       var validation = new AddTestValidator().Validation(entity);
       if (!validation.Succeeded) return validation.Fail();

       entity.Create();
       entity.Create_By = user?.UserName;
       entity.BusinessId = user?.BusinessId;

       return await base.Create(entity);
  }

  public async override Task> Update(Test entity, dynamic user)
  {
       var validation = new UpdateTestValidator().Validation(entity);
       if (!validation.Succeeded) return validation.Fail();

       entity.Update();
       entity.Update_By = user?.UserName;

       return await base.Update(entity);
  }

  public async Task>> List(Test model,PageInfo pager,dynamic user)
  {
       long? businessId = user?.BusinessId;

       var predicate = Expressionable.Create();
       predicate.And(q => q.BusinessId == businessId);
       
       var result = await Page(pager.PageIndex, pager.PageSize, predicate.ToExpression(), q => q.CreateTime, false);

       return result;
  }
}
//生成Dto
/// 
/// 测试表
/// 
public partial class TestDto
{
     /// 
  /// id
  /// 
  public long Id { get; set; }
     /// 
  /// 业务id
  /// 
  public long? BusinessId { get; set; }
     /// 
  /// 标题
  /// 
  public string Title { get; set; }
     /// 
  /// 内容
  /// 
  public string Content { get; set; }
     /// 
  /// 图片
  /// 
  public string Picture { get; set; }
     /// 
  /// 状态 0 正常 1 关闭
  /// 
  public int? Status { get; set; }
     /// 
  /// 备注说明
  /// 
  public string Remark { get; set; }
     /// 
  /// 排序
  /// 
  public int? Sort { get; set; }
  }
//生成控制器  BaseAppService 可自定义可继承 ControllerBase等
/// 
///  测试表
/// 
[Route("test")]
[Tags("测试表")]
public class TestAppService :BaseAppService
{
  private readonly ITestService service;
  

  public TestAppService(ITestService _service)
  {
     service = _service;
  }  
  /// 
  /// 创建测试表
  /// 
  /// 
  /// 
  
  [HttpPost]
  [SwaggerResponse(200, Type = typeof(IResult))]
  [Log(Title = "测试表", BusinessType = BusinessType.INSERT)]
  public IActionResult Create(TestDto model) => service.Create(model.Adapt(),User).ApiResult();

  /// 
  /// 修改测试表
  /// 
  /// 
  /// 
  
  [HttpPut]
  [SwaggerResponse(200, Type = typeof(IResult))]
  [Log(Title = "测试表", BusinessType = BusinessType.UPDATE)]
  public IActionResult Update(TestDto model) => service.Update(model.Adapt(),User).ApiResult();

  /// 
  /// 删除测试表
  /// 
  /// 
  /// 
  
  [HttpDelete("{id}")]
  [SwaggerResponse(200, Type = typeof(IResult))]
  [Log(Title = "测试表", BusinessType = BusinessType.DELETE)]
  public IActionResult Delete(int id) => service.Delete(q=>q.Id == id).ApiResult();

  /// 
  /// 获取测试表数据
  /// 
  /// 
  /// 
  
  [HttpGet("{id}")]
  [SwaggerResponse(200, Type = typeof(IResult))]
  public IActionResult Info(int id) => service.Info(q => q.Id == id).ApiResult();

  /// 
  /// 测试表列表
  /// 
  /// 
  /// 
  /// 
  [HttpGet("list")]
  [SwaggerResponse(200, Type = typeof(IResult>))]
  public IActionResult List(TestDto model,PageInfo pager) => service.List(model.Adapt(), pager, User).ApiResult();
 
}


Swagger显示效果

注:需要Demo请私信发邮箱
展开阅读全文

页面更新:2024-04-11

标签:代码   逗号   控制器   备注   状态   业务   标题   测试   时间   内容

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top