当前位置:科学 > 正文

Net 6.0中实现自动生成代码

2023-03-20 22:46:38  来源:简单d猫


(资料图)

1、前言

生成代码NuGet包:XmSoft.CodeGenerator

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

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

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

2、示例

//创建控制台应用 输出项目名称自定义dotnet new console -o XmSoft.AutoCode //引入NuGetdotnet 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<string>();    }}
//Program.cs Console.WriteLine("自动生成代码");var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();var options = configuration.GetSection(nameof(CodeHelperOptions)).Get<CodeHelperOptions>();var path = Directory.GetCurrentDirectory();var filterA= @"\XmSoft.AutoCode\bin\Debug\net6.0"; //XmSoft.AutoCode 修改创建的项目名var filterB = @"\XmSoft.AutoCode\bin\Release\net6.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

执行

//生成实体/// <summary>/// 测试表/// </summary>[SugarTable("z_test")]public partial class Test : BaseBusinessEntity<int?>{     /// <summary>  /// 标题  /// </summary> [SugarColumn(ColumnName = "title")]  public string Title { get; set; }     /// <summary>  /// 内容  /// </summary> [SugarColumn(ColumnName = "content")]  public string Content { get; set; }     /// <summary>  /// 图片  /// </summary> [SugarColumn(ColumnName = "picture")]  public string Picture { get; set; }     /// <summary>  /// 状态 0 正常 1 关闭  /// </summary> [SugarColumn(ColumnName = "status")]  public int? Status { get; set; }     /// <summary>  /// 备注说明  /// </summary> [SugarColumn(ColumnName = "remark")]  public string Remark { get; set; }     /// <summary>  /// 排序  /// </summary> [SugarColumn(ColumnName = "sort")]  public int? Sort { get; set; }  }    说明:自定义 BaseBusinessEntity或BaseEntity 自定义,这里的主键名id ,业务id    /// <summary>/// /// </summary>/// <typeparam name="T"></typeparam>public abstract class BaseBusinessEntity<T> : BaseEntity<T>{    /// <summary>    /// 业务Id    /// </summary>    [SugarColumn(ColumnName = "business_id")]    public long? BusinessId { get; set; }}public abstract class BaseEntity<T> {    [SugarColumn(IsPrimaryKey = true, IsIdentity = true, ColumnName = "id")]    public T Id { get; set; }    /// <summary>    /// 0未删除 1回收站 2已删除    /// </summary>    [SugarColumn(ColumnName = "delFlag")]    [JsonIgnore]    public string DelFlag { get; set; }    /// <summary>    /// 创建时间    /// </summary>    [SugarColumn(ColumnName = "create_time")]    // [Column("create_time")]    //[JsonIgnore]    public DateTime? CreateTime { get; set; }    /// <summary>    /// 创建Id    /// </summary>    [SugarColumn(ColumnName = "create_by")]    //[Column("create_id")]    [JsonIgnore]    public string Create_By { get; set; }    /// <summary>    /// 修改时间    /// </summary>    [SugarColumn(ColumnName = "update_time")]    //[Column("update_time")]    [JsonIgnore]    public DateTime? UpdateTime { get; set; }    /// <summary>    /// 修改者ID    /// </summary>    [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<Test> 引用XmSoft.Core.SqlSugar.Repositorypublic sealed class TestRepository :EFRepository<Test>,ITestRepository{  public readonly ISqlSugarClient Context;  public TestRepository(ISqlSugarClient context) : base(context) {     Context = context; } public ISugarQueryable<Test> SugarQueryable() {     return Context.Queryable<Test>(); }}
//生成服务 引用XmSoft.Core.SqlSugar.Servicepublic class TestService : BaseService<Test>,ITestService{  public TestService(ITestRepository _repository):base(_repository)  {  }    public async override Task<IResult<bool>> Create(Test entity, dynamic user)  {       var validation = new AddTestValidator().Validation(entity);       if (!validation.Succeeded) return validation.Fail<bool>();       entity.Create();       entity.Create_By = user?.UserName;       entity.BusinessId = user?.BusinessId;       return await base.Create(entity);  }  public async override Task<IResult<int>> Update(Test entity, dynamic user)  {       var validation = new UpdateTestValidator().Validation(entity);       if (!validation.Succeeded) return validation.Fail<int>();       entity.Update();       entity.Update_By = user?.UserName;       return await base.Update(entity);  }  public async Task<IResult<Page<Test>>> List(Test model,PageInfo pager,dynamic user)  {       long? businessId = user?.BusinessId;       var predicate = Expressionable.Create<Test>();       predicate.And(q => q.BusinessId == businessId);              var result = await Page(pager.PageIndex, pager.PageSize, predicate.ToExpression(), q => q.CreateTime, false);       return result;  }}
//生成Dto/// <summary>/// 测试表/// </summary>public partial class TestDto{     /// <summary>  /// id  /// </summary>  public long Id { get; set; }     /// <summary>  /// 业务id  /// </summary>  public long? BusinessId { get; set; }     /// <summary>  /// 标题  /// </summary>  public string Title { get; set; }     /// <summary>  /// 内容  /// </summary>  public string Content { get; set; }     /// <summary>  /// 图片  /// </summary>  public string Picture { get; set; }     /// <summary>  /// 状态 0 正常 1 关闭  /// </summary>  public int? Status { get; set; }     /// <summary>  /// 备注说明  /// </summary>  public string Remark { get; set; }     /// <summary>  /// 排序  /// </summary>  public int? Sort { get; set; }  }
//生成控制器  BaseAppService 可自定义可继承 ControllerBase等/// <summary>///  测试表/// </summary>[Route("test")][Tags("测试表")]public class TestAppService :BaseAppService{  private readonly ITestService service;    public TestAppService(ITestService _service)  {     service = _service;  }    /// <summary>  /// 创建测试表  /// </summary>  /// <param name="model"></param>  /// <returns></returns>    [HttpPost]  [SwaggerResponse(200, Type = typeof(IResult<bool>))]  [Log(Title = "测试表", BusinessType = BusinessType.INSERT)]  public IActionResult Create(TestDto model) => service.Create(model.Adapt<Test>(),User).ApiResult();  /// <summary>  /// 修改测试表  /// </summary>  /// <param name="model"></param>  /// <returns></returns>    [HttpPut]  [SwaggerResponse(200, Type = typeof(IResult<int>))]  [Log(Title = "测试表", BusinessType = BusinessType.UPDATE)]  public IActionResult Update(TestDto model) => service.Update(model.Adapt<Test>(),User).ApiResult();  /// <summary>  /// 删除测试表  /// </summary>  /// <param name="id"></param>  /// <returns></returns>    [HttpDelete("{id}")]  [SwaggerResponse(200, Type = typeof(IResult<int>))]  [Log(Title = "测试表", BusinessType = BusinessType.DELETE)]  public IActionResult Delete(int id) => service.Delete(q=>q.Id == id).ApiResult();  /// <summary>  /// 获取测试表数据  /// </summary>  /// <param name="id"></param>  /// <returns></returns>    [HttpGet("{id}")]  [SwaggerResponse(200, Type = typeof(IResult<Test>))]  public IActionResult Info(int id) => service.Info(q => q.Id == id).ApiResult();  /// <summary>  /// 测试表列表  /// </summary>  /// <param name="model"></param>  /// <param name="pager"></param>  /// <returns></returns>  [HttpGet("list")]  [SwaggerResponse(200, Type = typeof(IResult<Page<Test>>))]  public IActionResult List(TestDto model,PageInfo pager) => service.List(model.Adapt<Test>(), pager, User).ApiResult(); }


Swagger显示效果

注:需要Demo请私信发邮箱

关键词:

推荐阅读

手机卡服务密码怎么查?短信的找回方式的步骤

手机卡服务密码怎么查?当我们在办理手机业务或者兑换礼品的时,都需要用到手机号码的服务密码。那怎查询呢,比如可以去营业厅办理密码重置 【详细】

女娲补天背后有秘密 女娲补天的恐怖真相介绍

女娲补天背后有秘密相信每个人都听过女娲补天的故事,故事很有趣,结局也很很好。女娲拯救了人类,但是最近有人发现女娲补天背后有秘密,似 【详细】

飞机发明者是谁?飞机有哪些类型?

飞机发明者是谁?飞机是由莱特兄弟发明的,莱特兄弟是美国著名的发明家,他们的哥哥是威尔伯菜特,他们的弟弟是奥维尔莱特。1903年12月17日 【详细】

Google I/O线上开发者大会发布 安卓12新特性支持什么功能?

现在大多数人用的手机还是安卓机,本次Android 12的发布自然也是引起了一大波的关注,国内不少厂商也参与了测试,我们来看看谷歌正式发布A 【详细】

航天员出舱七个小时怎么喝水?太空行走的危险和好处是什么?

航天员出舱七个小时怎么喝水?7月4日,中国宇航员刘伯明和汤洪波出航活动,整个进程持续了7个多小时。据报道,宇航员在舱外服里有饮水袋,在 【详细】

关于我们  |  联系方式  |  免责条款  |  招聘信息  |  广告服务  |  帮助中心

联系我们:85 572 98@qq.com备案号:粤ICP备18023326号-40

科技资讯网 版权所有