//查询我的知识分享列表 public Response <List <KnowledegeShareList> > GetMyKnowledgeShareList(KnowledegeInput input) { Response <List <KnowledegeShareList> > response = new Response <List <KnowledegeShareList> >(); try { List <KnowledegeShareList> knowledegeShareLists = new List <KnowledegeShareList>(); Expression <Func <FileShare, bool> > filter = x => x.JobNum == input.JobNum && x.Status == input.Status; Func <IQueryable <FileShare>, IOrderedQueryable <FileShare> > orderBy = x => x.OrderByDescending(o => o.CreateTime); //计算总数目 response.TotalCount = _repository.Get(filter, orderBy).Count(); response.PageIndex = input.PageIndex; response.PageSize = input.PageSize; //查询 var queryresult = _repository.Get(filter, orderBy).Skip((input.PageIndex - 1) * input.PageSize).Take(input.PageSize).ToList(); //knowledegeShareList.Titile=queryresult foreach (var item in queryresult) { KnowledegeShareList knowledegeShareList = new KnowledegeShareList(); knowledegeShareList = ExpressionGenericMapper <FileShare, KnowledegeShareList> .Trans(item); knowledegeShareLists.Add(knowledegeShareList); } response.Data = knowledegeShareLists; } catch (Exception ex) { response.Status = 0; response.Msg = ex.Message.ToString(); } return(response); }
public static void Show() { { //Hard copy people to peopleCopy People people = new People() { Id = 11, Name = "Eleven", Age = 31 }; PeopleCopy peopleCopy = new PeopleCopy() { Id = people.Id, Name = people.Name, Age = people.Age }; //By reflection, fit different type of classes. var resultReflection = ReflectionMapper.Trans <People, PeopleCopy>(people); //By serialization var resultSerialization = SerializaMapper.Trans <People, PeopleCopy>(people); //By expression, 1. generic, 2. high performance. Could hard program dynamically and cache the result. var resultExpression = ExpressionGenericMapper <People, PeopleCopy> .Trans(people); var resultExpression1 = ExpressionGenericMapper <People, PeopleCopy> .Trans(people); } }
public static void MapToTest() { var student11 = new Student1() { Id = 1, Name = "wf", Pic = "wfpic" }; var student33 = new Student3() { Id = 1, Name = "wf" }; #region 方案一 var student2 = Mapping.MapTo <Student2>(student11); var student3 = Mapping.MapTo <Student3>(student11); var student4 = Mapping.MapTo <Student1>(student33); #endregion #region 方案二 var student5 = Mapping.JsonMapTo <Student2>(student11); var student6 = Mapping.JsonMapTo <Student2>(student33); #endregion #region 方案三 var student7 = Mapping.AutoMapperTo <Student2, Student1>(student11); var student8 = Mapping.AutoMapperTo <Student2, Student3>(student33); #endregion #region 方案四 var student9 = ExpressionGenericMapper.Map <Student1, Student2>(student11); var student10 = ExpressionGenericMapper.Map <Student3, Student2>(student33); #endregion }
/// <summary> /// 获取菜单对象 /// </summary> /// <param name="menusDbModel"></param> /// <returns></returns> private MenuTreeModel GetMenuTreeModel(TPMMenusDbModel menusDbModel) { var result = ExpressionGenericMapper <TPMMenusDbModel, MenuTreeModel> .Trans(menusDbModel); result.Children = new List <MenuTreeModel>(); return(result); }
/// <summary> /// 企业设置 /// </summary> /// <param name="requestObject"></param> /// <param name="UserID"></param> /// <returns></returns> public async Task <ResponseObject <TSMCompanyAllEditModel, bool> > ModifyCurentCompany(RequestObject <TSMCompanyAllEditModel> requestObject, int UserID) { //执行结果 var result = false; //没有修改信息,返回错误信息 if (requestObject.PostDataList == null && requestObject.PostData == null) { return(ResponseUtil <TSMCompanyAllEditModel, bool> .FailResult(requestObject, result, "PostData不能都为null")); } var curentDb = _db.Instance; int id = requestObject.PostData.ID; SMUserInfo sMUserInfo = SMCurentUserManager.GetCurentUserID(UserID, curentDb); if (sMUserInfo.CompanyId != id) { return(ResponseUtil <TSMCompanyAllEditModel, bool> .FailResult(requestObject, result, "只能修改自己公司")); } var companyDb = curentDb.Queryable <TSMCompanyDbModel>().Where(p => p.ID == id).First(); if (companyDb.AdminId != UserID) { return(ResponseUtil <TSMCompanyAllEditModel, bool> .FailResult(requestObject, result, "您不是公司管理员")); } try { curentDb.BeginTran(); var curentData = requestObject.PostData; var mainDb = ExpressionGenericMapper <TSMCompanyAllEditModel, TSMCompanyDbModel> .Trans(curentData); await curentDb.Updateable <TSMCompanyDbModel>(mainDb).UpdateColumns(p => new { p.CompanyName, p.LegalPerson, p.ContactNumber, p.EnterpriseType }).ExecuteCommandAsync(); var cDb = ExpressionGenericMapper <TSMCompanyAllEditModel, TTenantsModel> .Trans(curentData); cDb.ID = curentData.CId; await curentDb.Updateable <TTenantsModel>(cDb).UpdateColumns(p => new { p.TenantShortName, p.TenantEngName, p.TenantLogo, p.BusinessLogo }).ExecuteCommandAsync(); curentDb.CommitTran(); return(ResponseUtil <TSMCompanyAllEditModel, bool> .SuccessResult(requestObject, true)); } catch (Exception ex) { curentDb.RollbackTran(); return(ResponseUtil <TSMCompanyAllEditModel, bool> .FailResult(requestObject, result, ex.ToString())); } }
/// <summary> /// 修改T_Tenants数据 /// </summary> /// <param name="requestObject">返回响应结果对象,包括响应代码,修改操作结果</param> /// <returns></returns> public async Task <ResponseObject <TTenantsPutModel, bool> > PutAsync(RequestObject <TTenantsPutModel> requestObject) { try { //执行结果 var result = false; //没有修改信息,返回错误信息 if (requestObject.PostDataList == null && requestObject.PostData == null) { return(ResponseUtil <TTenantsPutModel, bool> .FailResult(requestObject, false, "PostData不能都为null")); } //批量更新优先级高于单记录更新 if (requestObject.PostDataList != null && requestObject.PostDataList.Count > 0) { //批量更新 // result = await _db.Instance.Updateable(requestObject.PostDataList).IgnoreColumns(p => new { p.BusinessLogo }).ExecuteCommandAsync() > 0; } else { _db.Instance.BeginTran(); int id = requestObject.PostData.ID; string name = requestObject.PostData.TenantName; var editModel = ExpressionGenericMapper <TTenantsPutModel, TTenantsModel> .Trans(requestObject.PostData); var idList = _db.Instance.Queryable <TSMCompanyDbModel>().Where(p => p.CompanyInfoId == id).Select(p => p.ID).ToList(); await _db.Instance.Updateable <TSMCompanyDbModel>().Where(p => idList.Contains(p.ID)).SetColumns(p => new TSMCompanyDbModel { ID = p.ID, CompanyName = name }).ExecuteCommandAsync(); //单记录更新 result = await _db.Instance.Updateable(editModel).IgnoreColumns(p => new { p.BusinessLogo, p.CreateId, p.CreateTime }).ExecuteCommandAsync() > 0; _db.Instance.CommitTran(); } //返回执行结果 if (result) { return(ResponseUtil <TTenantsPutModel, bool> .SuccessResult(requestObject, true)); } return(ResponseUtil <TTenantsPutModel, bool> .FailResult(requestObject, false, "修改数据失败!")); } catch (Exception ex) { _db.Instance.RollbackTran(); //返回异常结果 return(ResponseUtil <TTenantsPutModel, bool> .FailResult(requestObject, false, ex.Message)); } }
private List <ChinaAreaChildRecord> GetMenuTree(List <ChinaAreaRecord> aimData, int pid) { List <ChinaAreaChildRecord> tree = new List <ChinaAreaChildRecord>(); var children = aimData.Where(p => p.ParentArea_id == pid).ToList(); if (children.Count > 0) { foreach (var item in aimData.Where(p => p.ParentArea_id == pid).OrderBy(p => p.Code)) { ChinaAreaChildRecord node = ExpressionGenericMapper <ChinaAreaRecord, ChinaAreaChildRecord> .Trans(item); node.Children = GetMenuTree(aimData, item.ID); tree.Add(node); } } return(tree); }
private List <TSMDeptQueryTreeModel> GetMenuTree(List <TSMDeptQueryModel> aimData, int pid) { List <TSMDeptQueryTreeModel> tree = new List <TSMDeptQueryTreeModel>(); var children = aimData.Where(p => p.ParentId == pid).ToList(); if (children.Count > 0) { foreach (var item in aimData.Where(p => p.ParentId == pid).OrderBy(p => p.SeqNumber)) { TSMDeptQueryTreeModel node = ExpressionGenericMapper <TSMDeptQueryModel, TSMDeptQueryTreeModel> .Trans(item); node.Children = GetMenuTree(aimData, item.VitualId); tree.Add(node); } } return(tree); }
public async Task <Response <Post> > addView(KnowledegeInput input) { Response <Post> response = new Response <Post>(); try { var post = ExpressionGenericMapper <KnowledegeInput, Post> .Trans(input); await _mongoRepository.UpdateIncAsync <Post>(input.Id, new { Views = 1 }); var mongoent = await _mongoRepository.QueryAsync <Post>(p => p.PostGuid == input.PostGuid); response.Data = mongoent.FirstOrDefault(); } catch (Exception ex) { response.Status = 0; response.Msg = ex.Message.ToString(); } return(response); }
//发布知识分享 public async Task <Response <string> > MyKnowledgeSharePublish(KnowledegeInput input, string original) { Response <string> response = new Response <string>(); try { if (string.IsNullOrEmpty(input.Guid)) { input.Guid = Guid.NewGuid().ToString(); } input.PostGuid = input.Guid; FileShare fileShare = new FileShare(); Post post = new Post(); fileShare = ExpressionGenericMapper <KnowledegeInput, FileShare> .Trans(input); post = ExpressionGenericMapper <KnowledegeInput, Post> .Trans(input); post.State = input.Status; var mongoent = await _mongoRepository.InsertOrUpdateAsync(post); await _repository.InsertOrUpdate(fileShare, original, new List <string> { "JobNum", "Title", "Author", "Status" }); _repository.SaveChanges(); response.Data = mongoent.Id; } catch (Exception ex) { response.Status = 0; response.Msg = ex.Message.ToString(); //_repository.Dispose(); } return(response); }
/// <summary> /// 获取T_BM_CustomerFile主表数据数据 /// </summary> /// <param name="requestObject">Get请求参数</param> /// <param name="currentUser"></param> /// <returns>返回响应结果对象,包括响应代码,查询操作结果</returns> public async Task <ResponseObject <List <TBMCustomerFileQueryModel> > > GetMainListAsync(RequestGet requestObject, CurrentUser currentUser) { try { List <TBMCustomerFileQueryModel> queryData = new List <TBMCustomerFileQueryModel>(); //查询结果集对象 RefAsync <int> totalNumber = -1; //总记录数 var query = _db.Instance.Queryable <TBMCustomerFileDbModel, TBMCustomerContactDbModel>((t, t1) => new object[] { JoinType.Left, t1.CustomerId == t.ID }).Where((t, t1) => t.CompanyId == currentUser.CompanyID && t.DeleteFlag == false); //数据字典 List <TBMDictionaryCacheModel> dics = BasicCacheGet.GetDic(currentUser); List <ChinaAreaRecord> Areas = BasicCacheGet.GetChinaArea(currentUser); //查询条件 if (requestObject.QueryConditions != null && requestObject.QueryConditions.Count > 0) { var customerConditions1 = requestObject.QueryConditions.Where(p => p.Column.ToLower() == "contactname").ToList(); if (customerConditions1 != null && customerConditions1.Count() > 0) { var conditionals = SqlSugarUtil.GetConditionalModels(customerConditions1); foreach (ConditionalModel item in conditionals) { item.FieldName = $"t1.{item.FieldName}"; } query.Where(conditionals); } var customerConditions2 = requestObject.QueryConditions.Where(p => p.Column.ToLower() != "contactname").ToList(); if (customerConditions2 != null && customerConditions2.Count() > 0) { var conditionals = SqlSugarUtil.GetConditionalModels(customerConditions2); foreach (ConditionalModel item in conditionals) { item.FieldName = $"t.{item.FieldName}"; } query.Where(conditionals); } } //排序条件 if (requestObject.OrderByConditions != null && requestObject.OrderByConditions.Count > 0) { foreach (var item in requestObject.OrderByConditions) { var exp = SqlSugarUtil.GetOrderByLambda <TBMCustomerFileDbModel>(item.Column); if (exp == null) { continue; } if (item.Condition.ToLower() != "asc" && item.Condition.ToLower() != "desc") { continue; } query.OrderBy($"{item.Column} {item.Condition}"); } } var query1 = query.Select((t, t1) => t).Distinct(); List <TBMCustomerFileDbModel> queryDataTemp = new List <TBMCustomerFileDbModel>(); //执行查询 if (requestObject.IsPaging) { queryDataTemp = await query1 .Where(t => !t.DeleteFlag) .Select((t) => t) .ToPageListAsync(requestObject.PageIndex, requestObject.PageSize, totalNumber); } else { queryDataTemp = await query1 .Where(t => !t.DeleteFlag) .Select(t => t) .ToListAsync(); } queryDataTemp.ForEach((x) => { var itemEnity = ExpressionGenericMapper <TBMCustomerFileDbModel, TBMCustomerFileQueryModel> .Trans(x); itemEnity.ChildList = new List <TBMCustomerContactQueryModel>(); foreach (var citem in x.Child.OrderBy(p => p.Priority)) { var citemEnity = ExpressionGenericMapper <TBMCustomerContactDbModel, TBMCustomerContactQueryModel> .Trans(citem); itemEnity.ChildList.Add(citemEnity); } var item = dics.Where(p => p.ID == x.CustomerTypeId).FirstOrDefault(); if (item != null) { itemEnity.CustomerTypeName = item.DicValue; } if (x.IndustryId != null) { var industry = dics.Where(p => p.ID == x.IndustryId).FirstOrDefault(); if (x.IndustryId != null) { itemEnity.IndustryName = industry?.DicValue; } } if (!string.IsNullOrEmpty(x.City)) { var cityEntity = Areas.Where(p => p.Code == x.City).FirstOrDefault(); itemEnity.CityName = cityEntity?.FullName; } queryData.Add(itemEnity); }); //返回执行结果 return(ResponseUtil <List <TBMCustomerFileQueryModel> > .SuccessResult(queryData, totalNumber)); } catch (Exception ex) { //返回查询异常结果 return(ResponseUtil <List <TBMCustomerFileQueryModel> > .FailResult(null, ex.Message)); } }
public static void MapperTest() { People people = new People() { Id = 11, Name = "Eleven", Age = 31 }; long common = 0; long generic = 0; long cache = 0; long reflection = 0; long serialize = 0; { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 1000000; i++) { PeopleCopy peopleCopy = new PeopleCopy() { Id = people.Id, Name = people.Name, Age = people.Age }; } watch.Stop(); common = watch.ElapsedMilliseconds; } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 1000000; i++) { PeopleCopy peopleCopy = ReflectionMapper.Trans <People, PeopleCopy>(people); } watch.Stop(); reflection = watch.ElapsedMilliseconds; } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 1000000; i++) { PeopleCopy peopleCopy = SerializeMapper.Trans <People, PeopleCopy>(people); } watch.Stop(); serialize = watch.ElapsedMilliseconds; } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 1000000; i++) { PeopleCopy peopleCopy = ExpressionMapper.Trans <People, PeopleCopy>(people); } watch.Stop(); cache = watch.ElapsedMilliseconds; } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 1000000; i++) { PeopleCopy peopleCopy = ExpressionGenericMapper <People, PeopleCopy> .Trans(people); } watch.Stop(); generic = watch.ElapsedMilliseconds; } Console.WriteLine($"common = { common} ms"); Console.WriteLine($"reflection = { reflection} ms"); Console.WriteLine($"serialize = { serialize} ms"); Console.WriteLine($"cache = { cache} ms"); Console.WriteLine($"generic = { generic} ms"); }
public static void Show() { { Func <int, int, int> func = (m, n) => m * n + 2; // new Func<int, int, int>((m, n) => m * n + 2); Expression <Func <int, int, int> > exp = (m, n) => m * n + 2; //lambda表达式声明表达式目录树 //Expression<Func<int, int, int>> exp1 = (m, n) =>//只能一行 不能有大括号 // { // return m * n + 2; // }; //Queryable //a=>a.Id>3 //表达式目录树:语法树,或者说是一种数据结构;可以被我们解析 int iResult1 = func.Invoke(12, 23); int iResult2 = exp.Compile().Invoke(12, 23);//可以转换过去 } { Expression <Func <int, int, int> > exp = (m, n) => m * n + 2; ParameterExpression parameterExpression = Expression.Parameter(typeof(int), "m"); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(int), "n"); var multiply = Expression.Multiply(parameterExpression, parameterExpression2); var constant = Expression.Constant(2, typeof(int)); var add = Expression.Add(multiply, constant); Expression <Func <int, int, int> > expression = Expression.Lambda <Func <int, int, int> >( add, new ParameterExpression[] { parameterExpression, parameterExpression2 }); int iResult1 = exp.Compile().Invoke(11, 12); int iResult2 = expression.Compile().Invoke(11, 12); } //自己拼装表达式目录树 { //常量 ConstantExpression conLeft = Expression.Constant(345); ConstantExpression conRight = Expression.Constant(456); BinaryExpression binary = Expression.Add(conLeft, conRight); //345+456 Expression <Action> actExpression = Expression.Lambda <Action>(binary, null); //()=>345+456 //只能执行表示Lambda表达式的表达式目录树,即LambdaExpression或者Expression<TDelegate>类型。如果表达式目录树不是表示Lambda表达式,需要调用Lambda方法创建一个新的表达式 actExpression.Compile()(); //()=>345+456 } { ParameterExpression paraLeft = Expression.Parameter(typeof(int), "a"); //左边 ParameterExpression paraRight = Expression.Parameter(typeof(int), "b"); //右边 BinaryExpression binaryLeft = Expression.Multiply(paraLeft, paraRight); //a*b ConstantExpression conRight = Expression.Constant(2, typeof(int)); //右边常量 BinaryExpression binaryBody = Expression.Add(binaryLeft, conRight); //a*b+2 Expression <Func <int, int, int> > lambda = Expression.Lambda <Func <int, int, int> >(binaryBody, paraLeft, paraRight); Func <int, int, int> func = lambda.Compile();//Expression Compile成委托 int result = func(3, 4); } { Expression <Func <People, bool> > lambda = x => x.Id.ToString().Equals("5"); ParameterExpression parameterExpression = Expression.Parameter(typeof(People), "x"); var field = Expression.Field(parameterExpression, typeof(People).GetField("Id")); var toString = typeof(People).GetMethod("ToString"); var toStringCall = Expression.Call(field, toString, new Expression[0]); var equals = typeof(People).GetMethod("Equals"); var constant = Expression.Constant("5", typeof(string)); var equalsCall = Expression.Call(toStringCall, equals, new Expression[] { constant }); Expression <Func <People, bool> > expression = Expression.Lambda <Func <People, bool> >(equalsCall, new ParameterExpression[] { parameterExpression }); expression.Compile().Invoke(new People() { Id = 11, Name = "Eleven", Age = 31 }); } { ParameterExpression parameterExpression = Expression.Parameter(typeof(People), "x"); Expression field = Expression.Field(parameterExpression, typeof(People).GetField("Id")); MethodCallExpression toString = Expression.Call(field, typeof(People).GetMethod("ToString"), new Expression[0]); ConstantExpression constantExpression = Expression.Constant("5", typeof(string)); MethodCallExpression equals = Expression.Call(toString, typeof(People).GetMethod("Equals"), new Expression[] { constantExpression }); Expression <Func <People, bool> > lambda = Expression.Lambda <Func <People, bool> >(equals, new ParameterExpression[] { parameterExpression }); bool bResult = lambda.Compile()(new People() { Id = 11, Name = "Eleven", Age = 31 }); } { //以前根据用户输入拼装条件 string sql = "SELECT * FROM USER WHERE 1=1"; string name = "Eleven";//用户选择条件 if (string.IsNullOrWhiteSpace(name)) { sql += $" and name like '%{name}%'";//应该参数化 } //现在entityx framework查询的时候,需要一个表达式目录树 IQueryable <int> list = null; //都不过滤 1 if (true)//只过滤A 2 { //list=list.Where(); Expression <Func <People, bool> > exp1 = x => x.Id > 1; } if (true)//只过滤B 3 { //list=list.Where(); Expression <Func <People, bool> > exp2 = x => x.Age > 10; } //都过滤 4 Expression <Func <People, bool> > exp3 = x => x.Id > 1 && x.Age > 10; //2个条件 4种可能 排列组合 //3个条件 2的3次方 //list.Where() //拼装表达式目录树,交给下端用 //Expression<Func<People, bool>> lambda = x => x.Age > 5; ParameterExpression parameterExpression = Expression.Parameter(typeof(People), "x"); Expression propertyExpression = Expression.Property(parameterExpression, typeof(People).GetProperty("Age")); //Expression property = Expression.Field(parameterExpression, typeof(People).GetField("Id")); ConstantExpression constantExpression = Expression.Constant(5, typeof(int)); BinaryExpression binary = Expression.GreaterThan(propertyExpression, constantExpression);//添加方法的 Expression <Func <People, bool> > lambda = Expression.Lambda <Func <People, bool> >(binary, new ParameterExpression[] { parameterExpression }); bool bResult = lambda.Compile()(new People() { Id = 11, Name = "Eleven", Age = 31 }); } { People people = new People() { Id = 11, Name = "Eleven", Age = 31 }; PeopleCopy peopleCopy = new PeopleCopy() { Id = people.Id, Name = people.Name, Age = people.Age }; //硬编码 是不是写死了 只能为这两个类型服务 性能是最好的 { //反射 不同类型都能实现 var result = ReflectionMapper.Trans <People, PeopleCopy>(people); } { //序列化器 不同类型都能实现 var result = SerializeMapper.Trans <People, PeopleCopy>(people); } { //1 通用 2 性能要高 //能不能动态的生成硬编码,缓存起来 var result = ExpressionMapper.Trans <People, PeopleCopy>(people); } { var result = ExpressionMapper.Trans <People, PeopleCopy>(people); } { var result = ExpressionGenericMapper <People, PeopleCopy> .Trans(people); } { var result = ExpressionGenericMapper <People, PeopleCopy> .Trans(people); } //总结表达式目录树动态生成的用途了: //可以用来替代反射,因为反射可以通用,但是性能不够 //生成硬编码,可以提升性能 //automapper基于emit 动态生成硬编码 //Expression<Func<People, PeopleCopy>> lambda = p => // new PeopleCopy() // { // Id = p.Id, // Name = p.Name, // Age = p.Age // }; //lambda.Compile()(people); ParameterExpression parameterExpression = Expression.Parameter(typeof(People), "p"); List <MemberBinding> memberBindingList = new List <MemberBinding>(); foreach (var item in typeof(PeopleCopy).GetProperties()) { MemberExpression property = Expression.Property(parameterExpression, typeof(People).GetProperty(item.Name)); MemberBinding memberBinding = Expression.Bind(item, property); memberBindingList.Add(memberBinding); } foreach (var item in typeof(PeopleCopy).GetFields()) { MemberExpression property = Expression.Field(parameterExpression, typeof(People).GetField(item.Name)); MemberBinding memberBinding = Expression.Bind(item, property); memberBindingList.Add(memberBinding); } MemberInitExpression memberInitExpression = Expression.MemberInit(Expression.New(typeof(PeopleCopy)), memberBindingList.ToArray()); Expression <Func <People, PeopleCopy> > lambda = Expression.Lambda <Func <People, PeopleCopy> >(memberInitExpression, new ParameterExpression[] { parameterExpression }); Func <People, PeopleCopy> func = lambda.Compile(); PeopleCopy copy = func(people); } }
public async Task <ResponseObject <bool> > PostAsync(RequestPost <TMMBOMMainAddNewModel> requestObject, CurrentUser currentUser) { var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例 try { //没有新增数据,返回错误信息 if (requestObject.PostData == null) { return(ResponseUtil <bool> .FailResult(false, "PostData不能为null")); } //开启事务 currDb.BeginTran(); //删除以前的数据 int PackageId = requestObject.PostData.PackageId; TMMBOMMainDbModel oldDBMolde = _db.Instance.Queryable <TMMBOMMainDbModel>().Where(p => p.PackageId == PackageId).First(); if (oldDBMolde != null) { _db.Instance.Deleteable <TMMBOMDetailDbModel>().Where(p => p.MainId == PackageId).ExecuteCommand(); _db.Instance.Deleteable <TMMBOMMainDbModel>(oldDBMolde).ExecuteCommand(); } //插入主表数据 var mapMainModel = _mapper.Map <TMMBOMMainDbModel>(requestObject.PostData); var mainId = await currDb.Insertable(mapMainModel).ExecuteReturnIdentityAsync(); var materCache = BasicCacheGet.GetMaterial(currentUser); #region 处理配色项目 List <string> ItemList = requestObject.PostData.ChildList.Select(p => p.ItemName).Distinct().ToList(); Dictionary <string, int> itemToId = new Dictionary <string, int>(); foreach (string name in ItemList) { var colorItem = _db.Instance.Queryable <TMMPackageColorItemDbModel>().Where(p => p.CompanyId == currentUser.CompanyID && p.ItemName == name && p.PackageId == PackageId).First(); int ItemId = 0; if (colorItem == null) { TMMPackageColorItemDbModel temp = new TMMPackageColorItemDbModel(); temp.CompanyId = currentUser.CompanyID; temp.DeleteFlag = false; temp.PackageId = mapMainModel.PackageId; temp.ItemName = name; ItemId = _db.Instance.Insertable(temp).ExecuteReturnIdentity(); } else { ItemId = colorItem.ID; if (colorItem.DeleteFlag == true) { colorItem.DeleteFlag = false; _db.Instance.Updateable(colorItem).ExecuteCommand(); } } itemToId.Add(name, ItemId); } var itemIDs = _db.Instance.Queryable <TMMPackageColorItemDbModel>().Where(p => p.CompanyId == currentUser.CompanyID && p.PackageId == PackageId && !ItemList.Contains(p.ItemName)).Select(p => p.ID).ToList(); _db.Instance.Updateable <TMMPackageColorItemDbModel>().Where(p => itemIDs.Contains(p.ID)). SetColumns(it => new TMMPackageColorItemDbModel { DeleteFlag = true }).ExecuteCommand(); _db.Instance.Deleteable <TMMColorSolutionDetailDbModel>().Where(p => SqlFunc.Subqueryable <TMMColorSolutionMainDbModel>(). Where(p1 => p1.ID == p.MainId && p1.CompanyId == currentUser.CompanyID && p1.PackageId == PackageId).Any() && itemIDs.Contains(p.ItemId)); #endregion #region 处理部位 List <string> PartList = requestObject.PostData.ChildList.Where(p => !string.IsNullOrWhiteSpace(p.PartName)).Select(p => p.PartName).Distinct().ToList(); Dictionary <string, int> partId = new Dictionary <string, int>(); var dictionaryType = _db.Instance.Queryable <TBMDictionaryTypeDbModel>().Where(p => p.CompanyId == currentUser.CompanyID && p.TypeName == "部位档案").First(); foreach (string name in PartList) { var dicItem = _db.Instance.Queryable <TBMDictionaryDbModel>().Where(p => p.CompanyId == currentUser.CompanyID && p.DicValue == name).First(); int dicID = 0; if (dicItem == null) { TBMDictionaryDbModel temp = new TBMDictionaryDbModel(); temp.CompanyId = currentUser.CompanyID; temp.DeleteFlag = false; temp.TypeId = dictionaryType.ID; temp.DicValue = name; dicID = _db.Instance.Insertable(temp).ExecuteReturnIdentity(); } else { dicID = dicItem.ID; } partId.Add(name, dicID); } #endregion List <TMMBOMDetailDbModel> deatail = new List <TMMBOMDetailDbModel>(); foreach (TMMBOMDetailAddNewModel item in requestObject.PostData.ChildList) { TMMBOMDetailDbModel tMMBOMDetailDbModel = ExpressionGenericMapper <TMMBOMDetailAddNewModel, TMMBOMDetailDbModel> .Trans(item); tMMBOMDetailDbModel.MainId = mainId; tMMBOMDetailDbModel.ItemId = itemToId[item.ItemName]; if (!string.IsNullOrWhiteSpace(item.PartName)) { tMMBOMDetailDbModel.PartId = partId[item.PartName]; } if (!materCache.Any(p1 => p1.MaterialName == item.MaterialName)) { throw new Exception($"{item.MaterialName}物料不存在"); } deatail.Add(tMMBOMDetailDbModel); } //插入从表数据 // var mapDetailModelList = _mapper.Map<List<TMMBOMDetailAddNewModel>, List<TMMBOMDetailDbModel>>(requestObject.PostData.ChildList); var result = await currDb.Insertable(deatail).ExecuteCommandAsync() > 0; //提交事务 currDb.CommitTran(); //返回执行结果 return(result ? ResponseUtil <bool> .SuccessResult(true) : ResponseUtil <bool> .FailResult(false, "新增数据失败!")); } catch (Exception ex) { //回滚事务 currDb.RollbackTran(); //返回异常结果 return(ResponseUtil <bool> .FailResult(false, ex.Message)); } }
/// <summary> /// 新增 /// </summary> /// <param name="requestObject"></param> /// <param name="UserID">操作人ID</param> /// <returns></returns> public async Task <ResponseObject <TSMUserAccountAddAllModel, bool> > PostAsync(RequestObject <TSMUserAccountAddAllModel> requestObject, int UserID) { var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例 try { //没有新增数据,返回错误信息 if (requestObject.PostData == null) { return(ResponseUtil <TSMUserAccountAddAllModel, bool> .FailResult(requestObject, false, "PostData不能为null")); } //开启事务 currDb.BeginTran(); var user = _db.Instance.Queryable <TSMUserAccountDbModel, TSMCompanyDbModel>( (t, t1) => new object[] { JoinType.Left, t.CompanyId == t1.ID, }).Where((t, t1) => t.ID == UserID).Select((t, t1) => new { CompanyId = t.CompanyId, Name = t1.CompanyName }).First(); TSMUserAccountDbModel dbMain = ExpressionGenericMapper <TSMUserAccountAddAllModel, TSMUserAccountDbModel> .Trans(requestObject.PostData); //处理密码 dbMain.Salt = RandCodeCreate.GenerateRandomNumber(32); dbMain.Passwd = EncryptUtil.EnAESBykey(dbMain.Passwd, dbMain.Salt); dbMain.CreateTime = DateTime.Now; dbMain.CompanyId = user.CompanyId.Value; if (string.IsNullOrWhiteSpace(dbMain.EmailAccount)) { dbMain.EmailAccount = null; } if (string.IsNullOrWhiteSpace(dbMain.TelAccount)) { dbMain.TelAccount = null; } TSMUserInfoDbModel dbDeatail = ExpressionGenericMapper <TSMUserAccountAddAllModel, TSMUserInfoDbModel> .Trans(requestObject.PostData); //插入主表数据 var cId = await currDb.Insertable(dbDeatail).ExecuteReturnIdentityAsync(); dbMain.UserInfoId = cId; //插入从表数据 var mId = await currDb.Insertable(dbMain).ExecuteReturnIdentityAsync(); if (requestObject.PostData.RoleId != null && requestObject.PostData.RoleId > 0) { TSMRoleUserRelationDbModel itemEntity = new TSMRoleUserRelationDbModel(); itemEntity.RoleId = requestObject.PostData.RoleId.Value; itemEntity.UserId = mId; currDb.Insertable <TSMRoleUserRelationDbModel>(itemEntity).ExecuteCommand(); } if (requestObject.PostData.DeptId != null && requestObject.PostData.DeptId > 0) { TSMDeptUserRelationDbModel itemEntity = new TSMDeptUserRelationDbModel(); itemEntity.DeptId = requestObject.PostData.DeptId.Value; itemEntity.UserAccountId = mId; currDb.Insertable <TSMDeptUserRelationDbModel>(itemEntity).ExecuteCommand(); } //提交事务 currDb.CommitTran(); //返回执行结果 return(ResponseUtil <TSMUserAccountAddAllModel, bool> .SuccessResult(requestObject, true)); } catch (Exception ex) { //回滚事务 currDb.RollbackTran(); //返回异常结果 return(ResponseUtil <TSMUserAccountAddAllModel, bool> .FailResult(requestObject, false, ex.Message)); } }
/// <summary> /// 修改 /// </summary> /// <param name="requestObject"></param> /// <returns></returns> public async Task <ResponseObject <TSMUserAccountEditAllModel, bool> > PutAsync(RequestObject <TSMUserAccountEditAllModel> requestObject) { var currDb = _db.Instance;//事务需要使用同一个 SqlSugarClient对象实例 try { //没有新增数据,返回错误信息 if (requestObject.PostData == null) { return(ResponseUtil <TSMUserAccountEditAllModel, bool> .FailResult(requestObject, false, "PostData不能为null")); } //开启事务 currDb.BeginTran(); TSMUserAccountDbModel dbMain = ExpressionGenericMapper <TSMUserAccountEditAllModel, TSMUserAccountDbModel> .Trans(requestObject.PostData); dbMain.Salt = RandCodeCreate.GenerateRandomNumber(32); dbMain.Passwd = EncryptUtil.EnAESBykey(dbMain.Passwd, dbMain.Salt); if (string.IsNullOrWhiteSpace(dbMain.EmailAccount)) { dbMain.EmailAccount = null; } if (string.IsNullOrWhiteSpace(dbMain.TelAccount)) { dbMain.TelAccount = null; } TSMUserInfoDbModel dbDeatail = ExpressionGenericMapper <TSMUserAccountEditAllModel, TSMUserInfoDbModel> .Trans(requestObject.PostData); dbDeatail.ID = requestObject.PostData.CId; await currDb.Updateable(dbMain).IgnoreColumns(p => new { p.CreateTime, p.CompanyId, p.UserInfoId }).ExecuteCommandAsync(); await currDb.Updateable(dbDeatail).ExecuteCommandAsync(); currDb.Deleteable <TSMRoleUserRelationDbModel>().Where(p => p.UserId == dbMain.ID).ExecuteCommand(); if (requestObject.PostData.RoleId != null && requestObject.PostData.RoleId > 0) { TSMRoleUserRelationDbModel itemEntity = new TSMRoleUserRelationDbModel(); itemEntity.RoleId = requestObject.PostData.RoleId.Value; itemEntity.UserId = dbMain.ID; currDb.Insertable <TSMRoleUserRelationDbModel>(itemEntity).ExecuteCommand(); } currDb.Deleteable <TSMDeptUserRelationDbModel>().Where(p => p.UserAccountId == dbMain.ID).ExecuteCommand(); if (requestObject.PostData.DeptId != null && requestObject.PostData.DeptId > 0) { TSMDeptUserRelationDbModel itemEntity = new TSMDeptUserRelationDbModel(); itemEntity.DeptId = requestObject.PostData.DeptId.Value; itemEntity.UserAccountId = dbMain.ID; currDb.Insertable <TSMDeptUserRelationDbModel>(itemEntity).ExecuteCommand(); } //提交事务 currDb.CommitTran(); //返回执行结果 return(ResponseUtil <TSMUserAccountEditAllModel, bool> .SuccessResult(requestObject, true)); } catch (Exception ex) { //回滚事务 currDb.RollbackTran(); //返回异常结果 return(ResponseUtil <TSMUserAccountEditAllModel, bool> .FailResult(requestObject, false, ex.Message)); } }
public static void MapperTest() { { //People people = new People() //{ // Id = 11, // Name = "Richard", // Age = 31 //}; //PeopleCopy peopleCopy = new PeopleCopy()//硬编码 //硬编码性能好,但是通用型差 //{ // Id = people.Id, // Name = people.Name, // Age = people.Age //}; ////如果说有其他别的类型需要转换,那么不是为所有的类型都需要写这样代码? //PeopleCopy peopleCopy1 = ReflectionMapper.Trans<People, PeopleCopy>(people);//反射+泛型方法 //PeopleCopy peopleCopy2 = SerializeMapper.Trans<People, PeopleCopy>(people); ////Func<People, PeopleCopy> exp1 = p => ////{ //// return new PeopleCopy() //// { //// Id = p.Id, //// Name = p.Name, //// Age = p.Age //// }; ////}; ////泛型方法+表达式目录 = 既可以通用,效率高 //PeopleCopy peopleCopy3 = ExpressionMapper.Trans<People, PeopleCopy>(people); //PeopleCopy peopleCopy4 = ExpressionGenericMapper<People, PeopleCopy>.Trans(people); } { Console.WriteLine("****************************性能测试结果***************************"); People people = new People() { Id = 11, Name = "Richard", Age = 31 }; long common = 0; long generic = 0; long cache = 0; long reflection = 0; long serialize = 0; { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 100_000; i++) { PeopleCopy peopleCopy = new PeopleCopy() { Id = people.Id, Name = people.Name, Age = people.Age }; } watch.Stop(); common = watch.ElapsedMilliseconds; } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 100_000; i++) { PeopleCopy peopleCopy = ReflectionMapper.Trans <People, PeopleCopy>(people); } watch.Stop(); reflection = watch.ElapsedMilliseconds; } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 100_000; i++) { PeopleCopy peopleCopy = SerializeMapper.Trans <People, PeopleCopy>(people); } watch.Stop(); serialize = watch.ElapsedMilliseconds; } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 100_000; i++) { PeopleCopy peopleCopy = ExpressionMapper.Trans <People, PeopleCopy>(people); } watch.Stop(); cache = watch.ElapsedMilliseconds; } { Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 0; i < 100_000; i++) { PeopleCopy peopleCopy = ExpressionGenericMapper <People, PeopleCopy> .Trans(people); } watch.Stop(); generic = watch.ElapsedMilliseconds; } Console.WriteLine($"common = { common} ms"); Console.WriteLine($"reflection = { reflection} ms"); Console.WriteLine($"serialize = { serialize} ms"); Console.WriteLine($"cache = { cache} ms"); Console.WriteLine($"generic = { generic} ms"); } //通过拼接表达式目录树+ 泛型缓存性能最高! //硬编码性能最高,为了通用,动态生成硬编码==最完美 }