|
C#TMS系统代码-基础页面BaseCity学习
本人纯新手,刚进公司跟领导报道,我说我是java全栈,他问我会不会C#,我说大学学过,他说这个TMS系统就给你来管了。外包已经把代码给我了,这几天先把增删改查的代码背一下,说不定后面就要赶鸭子上架了
Service页面
- //using => import 导入
- using Microsoft.AspNetCore.Mvc;
- using SHZY.BaseData.Entitys.TMS.Dto.City;
- using SHZY.BaseData.Interfaces.TMS;
- ......
- //声明命名空间
- namespace SHZY.BaseData.TMS {
- //接口调用记录
- [ApiDescriptionSettings(Tag = "BaseData", Name = "TmsBaseCity", Order = 200)]
- //路由匹配
- [Route("api/TMS/BaseData/[controller]")]
- // : => implements 实现多接口
- public class TmsBaseCityService : ITmsBaseCityService, IDynamicApiController, ITransient {
- //Dao
- private readonly ISqlSugarRepository<TmsBaseCityEntity> _repository;//city的各种方法
- private readonly ITenant _db;//数据库事务
- private readonly IUserManager _userManager;//用户管理
- ......
- //初始化新实例
- public TmsBaseCityService(
- ISqlSugarRepository<TmsBaseCityEntity> tmsBaseCityRepository,
- ISqlSugarClient context,
- IUserManager userManager,
- ISqlSugarRepository<TmsBaseCityEntity> cityRepository) {
- _repository = tmsBaseCityRepository;
- _db = context.AsTenant();
- _userManager = userManager;
- }
- //各种方法
- ......
- }
- }
复制代码 查询单个City
- //get请求,id做参数
- [HttpGet("{id}")]
- //async-异步请求? Task-等待任务 dynamic-可变类型
- public async Task<dynamic> GetInfo(string id)
- {
- //await-等待这行完成 FirstOrDefaultAsync-返回结果集第一个,后面匿名函数查询规则id匹配 Adapt-转类型
- //链式写法,我不知道后面怎么打断点调试
- return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<TmsBaseCityInfoOutput>();
- }
复制代码 查询City分页List
- [HttpGet("")]
- //[FromQuery]-请求查询字符串参数,JSON格式(一般用于get)
- public async Task<dynamic> GetList([FromQuery] TmsBaseCityListQueryInput input)
- {
- //开查
- var queryable = _repository.Context.Queryable<TmsBaseCityEntity>()
- //判断查询参数是否为空,不为空用Contains判断是否包含(有多个也能满足)
- .WhereIF(!string.IsNullOrEmpty(input.name), it => it.Name.Contains(input.name))
- .......
- //直接where里面的条件
- .Where(it => it.DeleteMark == null)
- //把结果集数据转成要输出的类
- //似乎每种业务场景都会有变种类,这个是查询List的输出类 这是TMS系统的格式要求?
- .Select(it => new TmsBaseCityListOutput
- {
- id = it.Id,
- countryNo = it.CountryNo,
- ......
- })
- //两个或多个表的行合并到一个结果集中
- .MergeTable();
- //判断排序,为什么不用OrderByIF连着写算了
- if (!string.IsNullOrEmpty(input.sidx))
- {
- queryable.OrderBy(input.sidx + " " + input.sort);
- }
- else
- {
- queryable.OrderBy(it => it.id);
- }
- //带上页数和条数转分页 如果不分页直接ToListAsync()返回
- var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
- //转PageResult分页类型
- return PageResult<TmsBaseCityListOutput>.SqlSugarPageResult(data);
- }
复制代码 新增City
- [HttpPost("")]
- //[FromBody]-请求正文,JSON格式(一般用于post)
- public async Task Create([FromBody] TmsBaseCityCrInput input)
- {
- //AnyAsync判断有没有满足条件的结果(即数据库已有要新增的对象)
- if (await _repository.AnyAsync(it => it.CountryNo == input.countryNo && it.ProvinceNo == input.provinceNo && it.ProvinceName == input.provinceName && it.No == input.no && it.Name == input.name && it.DeleteMark == null))
- //抛出错误,ErrorCode是枚举,里面有各种报错信息
- throw Oops.Oh(ErrorCode.COM1004);
- var entity = input.Adapt<TmsBaseCityEntity>();
- //Insertable-插入数据 IgnoreColumns-忽略为null的列 CallEntityMethod-在插入数据库之前,对实体类的某个方法进行调用 ExecuteCommandAsync-执行
- var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
- //如果isOk不大于0,抛出错误
- if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
- }
复制代码 更新City
- //put请求,id做参
- [HttpPut("{id}")]
- public async Task Update(string id, [FromBody] TmsBaseCityUpInput input)
- {
- //AnyAsync判断有没有满足条件的结果(数据库id不同其他数据相同)
- if (await _repository.AnyAsync(it => it.CountryNo == input.countryNo && it.ProvinceNo == input.provinceNo && it.ProvinceName == input.provinceName && it.No == input.no && it.Name == input.name && it.DeleteMark == null && it.Id != input.id))
- throw Oops.Oh(ErrorCode.COM1004);
- //Adapt转一下类型
- var entity = input.Adapt<TmsBaseCityEntity>();
- //Updateable-修改数据 UpdateColumns-修改那些数据列 ExecuteCommandAsync-执行
- var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
- {
- it.CountryNo,
- ......
- }).ExecuteCommandAsync();
- if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
- }
复制代码 删除City
- //Delete请求
- [HttpDelete("{id}")]
- public async Task Delete(string id)
- {
- //没有删掉,只是更改DeleteMark,这里的写法类似写sql了
- //ExecuteCommandHasChangeAsync-返回一个布尔值表示是否有变更
- var isOk = await _repository.Context.Updateable<TmsBaseCityEntity>().SetColumns(it => new TmsBaseCityEntity()
- {
- DeleteTime = DateTime.Now,
- DeleteMark = 1,
- DeleteUserId = _userManager.UserId
- }).Where(it => it.Id.Equals(id)).ExecuteCommandHasChangeAsync();
- if (!isOk) throw Oops.Oh(ErrorCode.COM1002);
- }
复制代码 批量删除City
- //这里为啥不用Delete?
- [HttpPost("batchRemove")]
- public async Task BatchRemove([FromBody] List<string> ids)
- {
- //In(it => it.Id, ids) 把数据全部先查出来
- var entitys = await _repository.Context.Queryable<TmsBaseCityEntity>().In(it => it.Id, ids).ToListAsync();
- if (entitys.Count > 0)
- {
- try
- {
- //开启事务
- _db.BeginTran();
- //批量删除城市信息维护,这边用的Where(it => ids.Contains(it.Id))
- var isOk = await _repository.Context.Updateable<TmsBaseCityEntity>().SetColumns(it => new TmsBaseCityEntity()
- {
- DeleteTime = DateTime.Now,
- DeleteMark = 1,
- DeleteUserId = _userManager.UserId
- }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();
- //关闭事务
- _db.CommitTran();
- }
- catch (Exception)
- {
- //回滚事务
- _db.RollbackTran();
- throw Oops.Oh(ErrorCode.COM1002);
- }
- }
- }
复制代码 导出
- [HttpGet("Actions/Export")]
- public async Task<dynamic> Export([FromQuery] TmsBaseCityListQueryInput input)
- {
- var exportData = new List<TmsBaseCityListOutput>();
- //导出全部或者当前数据
- if (input.dataType == 0)
- //创建粘土对象转List<TmsBaseCityListOutput>
- exportData = Clay.Object(await GetList(input)).Solidify<PageResult<TmsBaseCityListOutput>>().list;
- else
- exportData = await GetNoPagingList(input);
- //导出数据列,JSON格式字符串直接ToList<ParamsModel>()手工转
- List<ParamsModel> paramList = "[{"value":"国家代码","field":"countryNo"},{"value":"省份代码","field":"provinceNo"},{"value":"省份名称","field":"provinceName"},{"value":"城市代码","field":"no"},{"value":"城市名称","field":"name"},{"value":"有效标志","field":"enabledMark"},]".ToList<ParamsModel>();
- //配置ExcelConfig
- ExcelConfig excelconfig = new ExcelConfig();
- excelconfig.FileName = "城市信息维护.xls";
- excelconfig.HeadFont = "微软雅黑";
- excelconfig.HeadPoint = 10;
- excelconfig.IsAllSizeColumn = true;
- excelconfig.ColumnModel = new List<ExcelColumnModel>();
- //selectKey=>用户选中的数据列
- foreach (var item in input.selectKey.Split(',').ToList())
- {
- var isExist = paramList.Find(p => p.field == item);
- //找到之后加入ColumnModel
- if (isExist != null)
- excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
- }
- //临时文件储存路径
- var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
- //导出
- ExcelExportHelper<TmsBaseCityListOutput>.Export(exportData, excelconfig, addPath);
- //excel文件路径
- var fileName = _userManager.UserId + "|" + addPath + "|xls";
- return new
- {
- //文件名
- name = excelconfig.FileName,
- //加密
- url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
- };
- }
复制代码 来源:https://www.cnblogs.com/fanwenkeer/p/18181616
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
|