使用c#生成非常简单的web api CRUD代码块

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

平时写CRUD太多重复的东西,然后自己写了特别简单的代码生成器,一个方法直接搞定,简单来说就是把通用的CRUD代码以字符串拼接的形式生成.cs文件。


一、非常简单的方法

1.方法代码块,ORM用的是sqlsugar

代码如下(示例):

            //models命名空间
            string modelsNameSpace = "lezuji_merchant.Models";
            //控制器命名空间
            string controllerSpace = "lezuji_merchant.Controllers.V1.Client";
            //sqlhelper全名
            string sqlHelperSpace = "LocalService.Sql.Helper";
            //可使用反射获取,这里我用的直接是model数组
            //var assembly = Assembly.Load(modelsNameSpace);

            Type[] models = new Type[] {
                typeof(AD),
                typeof(Admin),
                typeof(BorrowOrder),
                typeof(Machine),
                typeof(OperationRecord),
                typeof(Proxy),
                typeof(ProxyMsg),
                typeof(Root),
                typeof(RootRole),
                typeof(TakeMoneyLog) };
            
            //MyRoot特性适用于控制权限的,根据自己需求可删除相关特性
            string rootAttr = "MyRoot";
            string getAttribute = "[HttpGet,"+rootAttr+"]";
            string addAttribute = "[HttpPost," + rootAttr + "]";
            string delAttribute = "[HttpDelete," + rootAttr + "]";
            string cagAttribute = "[HttpPut," + rootAttr + "]";

            //文件路径
            string currentPath = $"G:\\code\\" + modelsNameSpace;

            if(!System.IO.Directory.Exists(currentPath))
            {
                System.IO.Directory.CreateDirectory(currentPath);
            }
            string sqlhelper = "_sqlHelper";
           
            foreach(var item in models)
            {
                StringBuilder sb = new StringBuilder();

                //命名空间
                sb.Append(" using "+ modelsNameSpace+";");
                sb.AppendLine();
                sb.Append("using Microsoft.AspNetCore.Authorization;");
                sb.AppendLine();
                sb.Append("using Microsoft.AspNetCore.Mvc;");
                sb.AppendLine();
                sb.Append("using Microsoft.Extensions.Options;");
                sb.AppendLine();
                sb.Append("using SqlSugar;");
                sb.AppendLine();
                sb.Append("using System;");
                sb.AppendLine();
                sb.Append("using System.Threading.Tasks;");
                sb.AppendLine();
                sb.AppendLine();
                sb.AppendLine();
                sb.Append("namespace "+ controllerSpace);
                sb.AppendLine();
                sb.Append("{");
                sb.AppendLine();
                //路由
                sb.Append("[ApiController, Route(\"v1/client/[controller]/[action]\"), Authorize]");
                sb.AppendLine();
                sb.Append("public class "+item.Name+"Controller:BaseController");
                sb.AppendLine();
                sb.Append("{");

                sb.AppendLine();
                sb.Append("private readonly "+sqlHelperSpace+" _sqlHelper;");
                sb.AppendLine();
                //构造函数
                sb.Append("public "+item.Name+ "Controller(" + sqlHelperSpace+ " sqlHelper)");
                sb.AppendLine();
                sb.Append("{");
                sb.AppendLine();
                sb.Append("_sqlHelper = sqlHelper;");
                sb.Append("}");
                sb.AppendLine();
                //查看
                sb.Append("//基础代码自动生成");
                sb.AppendLine();
                sb.Append(getAttribute.Insert(getAttribute.Length-1, "(\"查看" + item.Name+ "\")"));
                sb.AppendLine();

                sb.Append("    public async Task<IActionResult> GetList(int index=1,int size=30)");

                sb.AppendLine();
                sb.Append("{");
                sb.AppendLine();
                sb.Append("    RefAsync<int> total = 0;");

                sb.AppendLine();

                sb.Append("    var data=await "+sqlhelper+ ".DB.Queryable<"+item.Name+ ">().ToPageListAsync(index, size, total);");

                sb.AppendLine();

                sb.Append("    return Ok(new { data, total.Value });");

                sb.AppendLine();
                sb.Append("}");

                sb.AppendLine();
                sb.AppendLine();

                //新增
                sb.Append("//基础代码自动生成");
                sb.AppendLine();
                sb.Append(addAttribute.Insert(addAttribute.Length - 1, "(\"新增" + item.Name + "\")"));
                sb.AppendLine();

                sb.Append("    public async Task<IActionResult> Add([FromForm]"+item.Name+" "+item.Name.ToLower()+")");
                sb.AppendLine();
                sb.Append("{");

                sb.AppendLine();

                sb.Append("    bool result=await "+sqlhelper+ ".DB.Insertable(" + item.Name.ToLower() + ").ExecuteCommandAsync()>0;");

                sb.AppendLine();

                sb.Append("    return YesOrNo(result);");
                sb.AppendLine();

                sb.Append("}");

                sb.AppendLine();
                sb.AppendLine();
                //删除
                sb.Append("//基础代码自动生成");
                sb.AppendLine();
                sb.Append(delAttribute.Insert(delAttribute.Length - 1, "(\"删除" + item.Name + "\")"));
                sb.AppendLine();

                sb.Append("    public async Task<IActionResult> Del([FromForm]int id)");
                sb.AppendLine();
                sb.Append("{");

                sb.AppendLine();

                sb.Append("    bool result=await " + sqlhelper + ".DB.Deleteable<" + item.Name + ">().Where(a=>a.id==id).ExecuteCommandAsync()>0;");

                sb.AppendLine();

                sb.Append("    return YesOrNo(result);");
                sb.AppendLine();

                sb.Append("}");
                sb.AppendLine();
                sb.AppendLine();
                //修改
                sb.Append("//基础代码自动生成");
                sb.AppendLine();
                sb.Append(cagAttribute.Insert(cagAttribute.Length - 1, "(\"修改" + item.Name + "\")"));
                sb.AppendLine();

                sb.Append("    public async Task<IActionResult> Cag([FromForm]" + item.Name + " " + item.Name.ToLower() + ")");
                sb.AppendLine();
                sb.Append("{");

                sb.AppendLine();

                sb.Append("    bool result=await " + sqlhelper + ".DB.Updateable(" + item.Name.ToLower() + ").ExecuteCommandAsync()>0;");

                sb.AppendLine();

                sb.Append("    return YesOrNo(result);");
                sb.AppendLine();

                sb.Append("}");

                sb.AppendLine();
                sb.Append("}");
                sb.AppendLine();
                sb.Append("}");
                byte[] crud = Encoding.UTF8.GetBytes(sb.ToString());

                if(System.IO.File.Exists(currentPath + $"\\" + item.Name + "Controller.cs"))
                {
                    System.IO.File.Delete(currentPath + $"\\" + item.Name + "Controller.cs");
                }
                using (System.IO.FileStream fs =new System.IO.FileStream(currentPath+$"\\"+item.Name+ "Controller.cs", System.IO.FileMode.CreateNew))
                {
                    fs.Write(crud, 0, crud.Length);
                    fs.Flush();
                    fs.Close();
                }
            }

2.生成的文件,可直接复制到controller文件夹下,然后修正下格式,有些可能没引用的添加引用就可以了

相应的控制器类
在这里插入图片描述

总结

例如:本文仅仅只是用字符串拼接的方式生成的文件,性能啥的就别介意了,控制器要是多的话还是可以省点时间的,当然这个只是非常简单的,还有很多开源的好用的,只是写来玩玩哈。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值