C#TMS系統代碼-基礎頁面BaseCity學習 本人純新手,剛進公司跟領導報道,我說我是java全棧,他問我會不會C#,我說大學學過,他說這個TMS系統就給你來管了。外包已經把代碼給我了,這幾天先把增刪改查的代碼背一下,說不定後面就要趕鴨子上架了 Service頁面 //using => impo ...
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")
};
}