public void IsAdmin() { var user = Resolve <IUserService>().FirstOrDefault(); var result = EntityDynamicService.IsAdmin(user.Id); Assert.NotNull(result); }
public override bool IsValid(object value) { if (value == null) { return(false); } var userId = value.ConvertToLong(); if (userId <= 0) { return(false); } var find = EntityDynamicService.GetSingleUser(userId); if (find == null) { return(false); } if (find.Status != Status.Normal) { return(false); } return(true); }
public void GetSingleUser() { var user = Resolve <IUserService>().FirstOrDefault(); var result = EntityDynamicService.GetSingleUser(user.Id); Assert.NotNull(result); Assert.Equal(result, user); }
/// <summary> /// Pageds the list style. /// 样式列表格式化 /// </summary> /// <param name="pageList"></param> /// <returns>PagedList<TEntity>.</returns> private PagedList <TEntity> PagedListStyle(PagedList <TEntity> pageList) { var entityType = typeof(TEntity); var entity = Activator.CreateInstance(typeof(TEntity)); var propertys = entityType.GetPropertiesFromCache(); var interpreter = new Interpreter(); // 如果类型中有UserId,和UserName则 将UserName转换 if (propertys.FirstOrDefault(r => r.Name == "UserName") != null && propertys.FirstOrDefault(r => r.Name == "UserId") != null) { var selectExpression = "user.UserId"; var dynamicSelect = interpreter.ParseAsDelegate <Func <TEntity, long> >(selectExpression, "user"); var userIds = pageList.Select(dynamicSelect).Distinct().ToList(); // 根据Id获取用户 var users = EntityDynamicService.GetUserListByIds(userIds); var userResult = new List <TEntity>(); foreach (var item in pageList) { var dynamicItem = (dynamic)item; var userExpression = $"user.UserId=={dynamicItem.UserId} "; users.Foreach(r => { var dynamicUser = (dynamic)r; if (dynamicUser.Id == dynamicItem.UserId) { var gradeConfig = EntityDynamicService.GetUserGrade(dynamicUser.GradeId); dynamicItem.UserName = $" <img src='{ApiImageUrl(gradeConfig.Icon)}' alt='{gradeConfig.Name}' class='user-pic' style='width:18px;height:18px;' /><a class='primary-link margin-8' title='{dynamicUser.UserName}({dynamicUser.Name}) 等级:{gradeConfig?.Name}'>{dynamicUser.UserName}({dynamicUser.Name})</a>"; //href='/Admin/User/Edit?id={dynamicUser.Id}' } }); userResult.Add(dynamicItem); } pageList = PagedList <TEntity> .Create(userResult, pageList.RecordCount, pageList.PageSize, pageList.PageIndex); } return(pageList); }
/// <summary> /// 通用表单验证 /// </summary> /// <param name="view">The 视图.</param> /// <param name="errorMessage">The error message.</param> protected static bool IsFormValid(ref dynamic view, out string errorMessage) { Type inputType = view.GetType(); var propertyInfos = inputType.GetPropertiesFromCache(); foreach (var item in propertyInfos) { try { var property = propertyInfos.FirstOrDefault(r => r.Name.Equals(item.Name, StringComparison.OrdinalIgnoreCase)); // 所有的特性 var attributes = property.GetAttributes(); var value = property?.GetValue(view); var stringValue = string.Empty; try { stringValue = value.ToString(); } catch (System.Exception ex) { Console.WriteLine(ex.Message); } var displayAttribute = attributes.FirstOrDefault(r => r.GetType() == typeof(DisplayAttribute)); var displayName = property.Name; if (displayAttribute != null) { displayName = ((DisplayAttribute)displayAttribute).Name; } foreach (var attribute in attributes) { // 验证必填 if (attribute.GetType() == typeof(RequiredAttribute)) { if (stringValue.IsNullOrEmpty()) { errorMessage = displayName + "不能为空"; return(false); } } // 验证长度大小 if (attribute.GetType() == typeof(StringLengthAttribute)) { if (stringValue.Length > ((StringLengthAttribute)attribute).MaximumLength) { errorMessage = displayName + $"长度不能超过{((StringLengthAttribute)attribute).MaximumLength}字符"; return(false); } } // 验证远程信息 if (attribute.GetType() == typeof(FieldAttribute)) { var fieldAttribute = (FieldAttribute)attribute; if (fieldAttribute.ValidType == ValidType.UserName || fieldAttribute.ValidType == ValidType.ParentUserName) { // 推荐人为空的时候,不验证 if (fieldAttribute.ValidType == ValidType.ParentUserName && stringValue.IsNullOrEmpty()) { break; } // 用户名为空的时候 if (fieldAttribute.ValidType == ValidType.UserName) { if (stringValue.IsNullOrEmpty()) { errorMessage = "用户名不能为空"; return(false); } } var user = EntityDynamicService.GetSingleUser(value.ToString()); var dynamicUser = user; if (dynamicUser == null) { errorMessage = $"用户名{value}不存在,请重新输入"; return(false); } if (dynamicUser.Status != Status.Normal) { errorMessage = $"用户{value},状态不正常,已被冻结或删除"; return(false); } // 推荐人为空的时候,不验证 if (fieldAttribute.ValidType == ValidType.ParentUserName && stringValue.IsNullOrEmpty()) { try { view.ParentUserId = dynamicUser.Id; } catch { } try { view.ParentId = dynamicUser.Id; } catch { } } // 用户Id动态转换 if (fieldAttribute.ValidType == ValidType.UserName) { try { view.UserId = dynamicUser.Id; } catch { } } } } } } catch (AggregateException filedException) { Console.WriteLine(filedException); } } var error = string.Empty; errorMessage = error; return(true); }
/// <summary> /// 支付完成后更新订单状态 /// 更新支付订单状态 /// </summary> /// <param name="entityIdList">The entity identifier list.</param> /// <param name="pay">The pay.</param> /// <param name="isPaySucess">是否支出成功</param> public ServiceResult AfterPay(List <object> entityIdList, Pay pay, bool isPaySucess) { var sqlList = new List <string>(); var sql = string.Empty; var result = ServiceResult.Success; //扣除解冻后的虚拟资产(支付成功后,冻结资产减少) foreach (var payPair in pay.AccountPayPair) { if (payPair.Value > 0) { var accountSql = $"select FreezeAmount from Asset_Account where MoneyTypeId='{payPair.Key}' and UserId={pay.UserId}"; var freezeAmount = RepositoryContext.ExecuteScalar(accountSql).ToDecimal(); if (freezeAmount < payPair.Value) { return(ServiceResult.Failure("冻结账户余额不足")); } // 扣除冻结资产 sql = $"update Asset_Account set FreezeAmount=FreezeAmount-{payPair.Value} where UserId={pay.UserId} and MoneyTypeId='{payPair.Key}'"; sqlList.Add(sql); // 财务记录 var intro = $"支付订单(编号{pay.PayExtension.TradeNo})后,减少冻结资产,减少金额{payPair.Value},冻结金额账后{freezeAmount - payPair.Value}"; sql = $@"INSERT INTO [dbo].[Asset_Bill]([UserId] ,[OtherUserId] ,[Type] ,[Flow] ,[MoneyTypeId],[Amount] ,[AfterAmount],[Intro] ,[CreateTime] ,[EntityId]) VALUES ({pay.UserId},0,{Convert.ToInt16(BillActionType.Shopping)},{ Convert.ToInt16(AccountFlow.Spending) },'{payPair.Key}',{-payPair.Value},{freezeAmount - payPair.Value},'{intro}',GETDATE(),{ pay.Id })"; sqlList.Add(sql); } } //支付成功 if (isPaySucess) { // 更新支付账单状态 sql = $"UPDATE [dbo].[Asset_Pay] SET [Message] = '{pay.Message}',[PayType]={Convert.ToInt16(pay.PayType)} ,[ResponseSerial] ='{pay.ResponseSerial}' ,[Status] =2 ,[ResponseTime] = '{pay.ResponseTime}' where id={pay.Id} and Status=1"; sqlList.Add(sql); // 插入分润订单 if (pay.Type == CheckoutType.Order) { //更新支付状态 var orderStatus = 2; // 代发货 if (pay.PayExtension.IsGroupBuy) { orderStatus = 10; // 如果是团购商品,状态改成待分享 } sql = $"update Shop_Order set OrderStatus={orderStatus},PayId='{pay.Id}' where OrderStatus=1 and id in ({entityIdList.ToSqlString()})"; sqlList.Add(sql); foreach (var item in entityIdList) { // 如果是管理员代付 var orderUserId = pay.UserId; if (pay.PayExtension?.OrderUser?.Id >= 0) // 订单Id使用实际订单Id { orderUserId = pay.PayExtension.OrderUser.Id; } if (pay.PayType == PayType.AdminPay) { var order = EntityDynamicService.GetSingleOrder((long)item); orderUserId = order.UserId; } // 通过支付记录,修改分入订单的触发类型 var triggerType = TriggerType.Order; if (Convert.ToInt16(pay.PayExtension.TriggerType) > 0) { triggerType = pay.PayExtension.TriggerType; } //TODO 2019年9月22日 订单完成后分润 重构 //var shareOrderConfig = Ioc.Resolve<IAutoConfigService>().GetValue<ShopOrderShareConfig>(); //int pending = (int)ShareOrderSystemStatus.Pending; //if (shareOrderConfig.OrderSuccess) { // pending = (int)ShareOrderSystemStatus.OrderPendingSucess; //} // 分润订单, UserId 有等于 OrderId的可能, 用 EntityId = {trade.Id}) AND TriggerType != 1 联合进行限制 sql = $" IF NOT EXISTS(SELECT * FROM Things_Trade WHERE EntityId = {(long)item} AND TriggerType != 1) " + "INSERT INTO [dbo].[Things_Trade]([UserId] ,[Amount] ,[EntityId],[Parameters] ,[Status],[SystemStatus] , [TriggerType] ,[Summary] ,[CreateTime] ,[UpdateTime],[Extension],[ExecuteCount]) " + $"VALUES ({orderUserId} ,{pay.Amount},{(long)item},'{string.Empty}' ,{(int)ShareOrderStatus.Pending} ,{(int)ShareOrderSystemStatus.Pending} ,{(int)triggerType} ,'{string.Empty}' ,'{DateTime.Now}' ,'{DateTime.Now}','',0)"; sqlList.Add(sql); // 订单操作记录 sql = "INSERT INTO [dbo].[Shop_OrderAction] ([OrderId] ,[ActionUserId] ,[Intro] ,[Extensions] ,[CreateTime],[OrderActionType])" + $"VALUES({(long)item},{pay.UserId},'会员支付订单,支付方式为{pay.PayType.GetDisplayName()},支付现金金额为{pay.Amount}','','{DateTime.Now}',102)"; sqlList.Add(sql); #region 如果是拼团购买 //更新活动记录状态 if (pay.PayExtension.IsGroupBuy) { sql = $"update Shop_ActivityRecord set Status=2 where OrderId={item} and Status=1"; sqlList.Add(sql); sql = $" select count(id) from Shop_ActivityRecord where ParentId = (select ParentId from Shop_ActivityRecord where OrderId = {item}) and ParentId> 0"; var gourpBuyCount = RepositoryContext.ExecuteScalar(sql).ConvertToLong(); if (gourpBuyCount > 0 && gourpBuyCount + 1 == pay.PayExtension.BuyerCount && pay.PayExtension.BuyerCount > 0) { // 拼团结束(修改订单状态) var parentId = RepositoryContext .ExecuteScalar($"select ParentId from Shop_ActivityRecord where OrderId={item}") .ConvertToLong(); //将订单状态从待分享修改成待发货 sql = $"update Shop_Order set OrderStatus=2 where Id in( select OrderId from Shop_ActivityRecord where (ParentId={parentId} or Id={parentId}) and Status=2) and OrderStatus=10"; sqlList.Add(sql); //修改活动记录支付状态,为成功 sql = $"update Shop_ActivityRecord set Status=5 where Id in( select Id from Shop_ActivityRecord where (ParentId={parentId} or Id={parentId}) and Status=2)"; sqlList.Add(sql); } } #endregion 如果是拼团购买 } } #region 支付时附加的Sql后操作 var excecuteSqlList = pay.PayExtension?.ExcecuteSqlList; if (excecuteSqlList != null) { // 动态调用执行 var resolveResult = DynamicService.ResolveMethod(excecuteSqlList.ServiceName, excecuteSqlList.Method, entityIdList); if (resolveResult.Item1.Succeeded) { var afterSqlList = (IList <string>)resolveResult.Item2; if (afterSqlList.Count > 0) { sqlList.AddRange(afterSqlList); } } } #endregion 支付时附加的Sql后操作 } //支付失败 else { if (pay.Type == CheckoutType.Order) { foreach (var payPair in pay.AccountPayPair) { if (payPair.Value > 0) { // 减少冻结资产 var accountSql = $"select Amount from Asset_Account where MoneyTypeId='{payPair.Key}' and UserId={pay.UserId}"; var amount = RepositoryContext.ExecuteScalar(accountSql).ToDecimal(); // 扣除冻结资产 sql = $"update Asset_Account set amount=amount+{payPair.Value} where UserId={pay.UserId} and MoneyTypeId='{payPair.Key}'"; sqlList.Add(sql); // 财务记录 var intro = $"支付订单(编号{pay.PayExtension.TradeNo})失败后,解冻金额,金额{payPair.Value},解冻账后{amount + payPair.Value}"; sql = $@"INSERT INTO [dbo].[Asset_Bill]([UserId] ,[OtherUserId] ,[Type] ,[Flow] ,[MoneyTypeId],[Amount] ,[AfterAmount],[Intro] ,[CreateTime] ,[EntityId]) VALUES ({pay.UserId},0,{Convert.ToInt16(BillActionType.Shopping)},{ Convert.ToInt16(AccountFlow.Income) },'{payPair.Key}',{payPair.Value},{amount + payPair.Value},'{intro}',GETDATE(),{ pay.Id })"; sqlList.Add(sql); } } } //更新数据库 } var count = RepositoryContext.ExecuteSqlList(sqlList); if (count <= 0) // Ioc. Resolve<IPayService>().Log("订单支付后,数据库相关处理失败", LogsLevel.Error); { return(ServiceResult.Failure("订单支付后,数据库相关处理失败")); } // 支付成功后处理 var afterSuccess = pay.PayExtension?.AfterSuccess; if (afterSuccess != null) // 动态调用执行 { DynamicService.ResolveMethod(afterSuccess.ServiceName, afterSuccess.Method, entityIdList); } return(result); }
/// <summary> /// 初始化所有的表服务 /// </summary> public void Init() { Resolve <ITableService>().DeleteAll(); if (!Exists()) { var tables = new List <Table>(); #region AutoConfig配置 // AutoConfig配置 var types = EntityDynamicService.GetAllAutoConfig(); foreach (var type in types) { var table = new Table { Key = type.Name, Type = type.FullName, TableType = TableType.AutoConfig, TableName = "Core_AutoConfig" }; if (type.FullName.Contains("ViewModels")) { continue; } if (type.FullName.Contains("Entities")) { continue; } if (!(type.FullName.Contains("Config") && type.Name != "AutoConfig")) { continue; } var classDescription = new ClassDescription(type); table.Name = classDescription?.ClassPropertyAttribute?.Name; foreach (var item in classDescription.Propertys.Where(r => r.Name == "Id")) { table.Columns.Add(GetColumn(item)); } var propertys = classDescription.Propertys.Where(r => r.Name != "Id" && r.Name != "HttpContext" && r.Name != "CreateTime"); foreach (var item in propertys) { table.Columns.Add(GetColumn(item)); } foreach (var item in classDescription.Propertys.Where(r => r.Name == "CreateTime")) { table.Columns.Add(GetColumn(item)); } tables.Add(table); } #endregion AutoConfig配置 #region 枚举 // AutoConfig配置 types = EntityDynamicService.GetAllEnum(); foreach (var type in types) { var table = new Table { Key = type.Name, Type = type.FullName, TableType = TableType.Enum, TableName = string.Empty }; foreach (var item in Enum.GetValues(type)) { var column = new TableColumn(); column.Key = Enum.GetName(type, item); column.Name = item.GetDisplayName(); table.Columns.Add(column); } tables.Add(table); } #endregion 枚举 #region 级联分类与标签 types = EntityDynamicService.GetAllRelationTypes(); foreach (var type in types) { var table = new Table { Key = type.Name, Type = type.FullName, TableName = "Basic_Relation" }; table.Columns = new List <TableColumn>(); var classDescription = new ClassDescription(type); table.Name = classDescription?.ClassPropertyAttribute?.Name; if (type.FullName.Contains("Class")) { table.TableType = TableType.ClassRelation; tables.Add(table); } if (type.FullName.Contains("Tag")) { table.TableType = TableType.TagRelation; tables.Add(table); } } #endregion 级联分类与标签 #region 实体类 types = RuntimeContext.Current.GetPlatformRuntimeAssemblies().SelectMany(a => a.GetTypes() .Where(t => t.GetInterfaces().Contains(typeof(IEntity)) || t.GetInterfaces().Contains(typeof(IMongoEntity)))); types = types.Where(r => r.IsGenericType == false); types = types.Where(r => r.IsAbstract == false); types = types.Where(r => r.IsInterface == false); types = types.Where(r => !r.FullName.Contains("Test.")); types = types.Where(r => !r.FullName.Contains("Tests.")); var sqlTables = EntityDynamicService.GetSqlTable(); foreach (var type in types) { var table = new Table { Key = type.Name, Type = type.FullName }; if (type.FullName.Contains("Config") && type.Name != "AutoConfig") { continue; } if (type.FullName.Contains("ViewModels")) { continue; } if (!type.FullName.Contains("Entities")) { continue; } if (type.BaseType.Name.Contains("Mongo")) { var tableAttribute = type.GetAttribute <TableAttribute>(); if (tableAttribute == null) { continue; } table.TableName = tableAttribute.Name; table.TableType = TableType.Mongodb; } else { table.TableType = TableType.SqlServer; var find = sqlTables.FirstOrDefault(r => r.EndsWith(table.Key)); if (find != null) { table.TableName = find; } } var classDescription = new ClassDescription(type); table.Name = classDescription?.ClassPropertyAttribute?.Name; foreach (var item in classDescription.Propertys.Where(r => r.Name == "Id")) { table.Columns.Add(GetColumn(item)); } var propertys = classDescription.Propertys.Where(r => r.Name != "Id" && r.Name != "HttpContext" && r.Name != "CreateTime"); foreach (var item in propertys) { table.Columns.Add(GetColumn(item)); } foreach (var item in classDescription.Propertys.Where(r => r.Name == "CreateTime")) { table.Columns.Add(GetColumn(item)); } tables.Add(table); } #endregion 实体类 AddMany(tables); } }
public void GetAllRelationTypes() { var result = EntityDynamicService.GetAllRelationTypes(); Assert.NotNull(result); }
public void GetAllEnum() { var result = EntityDynamicService.GetAllEnum(); Assert.NotNull(result); }
public void GetAllAutoConfig() { var result = EntityDynamicService.GetAllAutoConfig(); Assert.NotNull(result); }
public void GetSqlTable() { var result = EntityDynamicService.GetSqlTable(); Assert.NotNull(result); }
/// <summary> /// 获取s the 会员 output. /// 前端会员输出模型 /// </summary> /// <param name="userId">会员Id</param> public UserOutput GetUserOutput(long userId) { var user = Resolve <IUserService>().GetSingle(u => u.Id == userId); if (user == null) { throw new ValidException("用户不存在"); } var grade = Resolve <IGradeService>().GetGrade(user.GradeId); if (grade == null) { throw new ValidException("用户等级不存在"); } var detail = Resolve <IUserDetailService>().GetSingle(u => u.UserId == userId); if (detail == null) { throw new ValidException("用户详细信息不存在"); } user.Detail = detail; var userOutput = user.Detail.MapTo <UserOutput>(); userOutput.GradeName = Resolve <IGradeService>().GetGrade(user.GradeId)?.Name; userOutput.Status = user.Status.GetDisplayName(); userOutput.Avator = Resolve <IApiService>().ApiUserAvator(user.Id); if (!user.Detail.Avator.IsNullOrEmpty()) { userOutput.Avator = Resolve <IApiService>().ApiImageUrl(user.Detail.Avator); } userOutput.GradeIcon = Resolve <IApiService>().ApiImageUrl(grade?.Icon); userOutput.Sex = user.Detail.Sex.GetDisplayName(); userOutput.RegionName = Resolve <IRegionService>().GetFullName(user.Detail.RegionId); var userConfig = Resolve <IAutoConfigService>().GetValue <UserConfig>(); userOutput.ExpireTime = DateTime.Now.AddMinutes(userConfig.LoginExpirationTime).ConvertDateTimeInt(); userOutput.GradeName = grade?.Name; userOutput.Status = user.Status.GetDisplayName(); userOutput.Sex = user.Detail.Sex.GetDisplayName(); userOutput.UserName = user.UserName; userOutput.Email = user.Email; userOutput.Name = user.Name; userOutput.ParentId = user.ParentId; userOutput.GradeId = user.GradeId; userOutput.Id = user.Id; userOutput.Mobile = user.Mobile; userOutput.ParentUserName = Resolve <IUserService>().GetSingle(u => u.Id == user.ParentId)?.UserName; userOutput.IdentityStatusName = userOutput.IdentityStatus.GetDisplayName(); userOutput.OpenId = user.Detail.OpenId; var parentUser = Resolve <IUserService>().GetSingle(user.ParentId); if (parentUser != null) { userOutput.ParentUserName = parentUser.GetUserName(); } if (detail.PayPassword.IsNullOrEmpty()) { userOutput.IsNeedSetPayPassword = true; } userOutput.IsAdmin = Resolve <IUserService>().IsAdmin(user.Id); userOutput.Store = EntityDynamicService.GetStore(user.Id); userOutput.Token = Resolve <IUserService>().GetUserToken(user); return(userOutput); }
public PagedList <TEntity> GetPagedList(object paramater, Type searchView, Expression <Func <TEntity, bool> > predicate = null) { var query = new ExpressionQuery <TEntity> { EnablePaging = true }; #region 构建查询页数 var dictionary = paramater.DeserializeJson <Dictionary <string, string> >(); if (dictionary != null) { var pagedInput = AutoMapping.SetValue <PagedInputDto>(dictionary); if (pagedInput != null) { query.PageIndex = (int)pagedInput.PageIndex; query.PageSize = (int)pagedInput.PageSize; } } #endregion 构建查询页数 if (predicate != null) { query.And(predicate); } var result = HanderDictionary(ref dictionary); // 获取搜索范围相关的字段 var rangList = result.Item1; var interpreter = new Interpreter(); var classDescription = new ClassDescription(searchView); var propertyResults = searchView.GetPropertyResultFromCache(); var propertyInfos = propertyResults.Select(r => r.PropertyInfo); #region 普通字段搜索 foreach (var item in dictionary) { var name = item.Key.Replace("_Start", "").Replace("_End", ""); var value = item.Value.SafeString(); if (value.IsNullOrEmpty() || name.IsNullOrEmpty()) { continue; } if (name.Equals("UserName", StringComparison.OrdinalIgnoreCase)) { #region 搜索用户名 var property = propertyInfos.FirstOrDefault(r => r.Name.Equals("UserId", StringComparison.OrdinalIgnoreCase)); if (property == null) { continue; } var user = EntityDynamicService.GetSingleUser(value); // 动态获取用户名 if (user != null) { var expression = Lambda.Equal <TEntity>(property.Name, user.Id); query.And(expression); } #endregion 搜索用户名 } else if (name.Equals("Serial", StringComparison.OrdinalIgnoreCase)) { #region 搜索序号 // 序号处理,适合序号是通过Id生成的方式,比如Bill,Order,Reard表 var property = propertyInfos.FirstOrDefault(r => r.Name.Equals("Id", StringComparison.OrdinalIgnoreCase)); if (property == null) { continue; } if (value.Length > 7 && value.StartsWith("9")) { value = value.Substring(1, value.Length - 1); } // 去掉前面的0 var reg = new Regex(@"^0+"); value = reg.Replace(value, ""); var idValue = value.ConvertToLong(0); if (idValue > 0) { var expression = Lambda.Equal <TEntity>(property.Name, idValue); query.And(expression); } #endregion 搜索序号 } else { var property = propertyInfos.FirstOrDefault(r => r.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); if (property == null) { continue; } if (property.PropertyType.IsEnum) { if (value == "-1") { continue; } } var fieldAttribute = propertyResults.FirstOrDefault(r => r.PropertyInfo.Name == property.Name) .FieldAttribute; var valueList = value.ToSplitList(); foreach (var itemValue in valueList) { if (!itemValue.IsNullOrEmpty()) { Expression <Func <TEntity, bool> > expression = null; if (fieldAttribute != null) { if (fieldAttribute.Operator == Operator.Contains) { expression = Lambda.Contains <TEntity>(property.Name, itemValue); } if (fieldAttribute.Operator == Operator.Equal) { expression = Lambda.Equal <TEntity>(property.Name, itemValue); } } // 字段中包含name和title,一般都可以模糊搜索 else if (property.Name.Contains("name", StringComparison.OrdinalIgnoreCase) || property.Name.Contains("intro", StringComparison.OrdinalIgnoreCase) || property.Name.Contains("desc", StringComparison.OrdinalIgnoreCase) || property.Name.Contains("remark", StringComparison.OrdinalIgnoreCase) || property.Name.Contains("title", StringComparison.OrdinalIgnoreCase)) { expression = Lambda.Contains <TEntity>(property.Name, itemValue); } else { expression = Lambda.Equal <TEntity>(property.Name, itemValue); } if (expression != null) { query.And(expression); } } } } } #endregion 普通字段搜索 #region 搜索范围字段搜索 foreach (var item in rangList) { var property = propertyInfos.FirstOrDefault(r => r.Name.Equals(item.Name, StringComparison.OrdinalIgnoreCase)); if (property == null || item.StartValue.IsNullOrEmpty() && item.EndValue.IsNullOrEmpty()) { continue; } // 大于等于 if (!item.StartValue.IsNullOrEmpty()) { var expression = Lambda.GreaterEqual <TEntity>(property.Name, item.StartValue); if (expression != null) { query.And(expression); } } // 小于等于 if (!item.EndValue.IsNullOrEmpty()) { var expression = Lambda.LessEqual <TEntity>(property.Name, item.EndValue); if (expression != null) { query.And(expression); } } } #endregion 搜索范围字段搜索 #region 排序 var sortType = result.Item2; var propertySort = propertyInfos.FirstOrDefault(r => r.Name.Equals(sortType.Name, StringComparison.OrdinalIgnoreCase)); if (propertySort != null) { var selectExpression = $"entity.{propertySort.Name}"; var expression = interpreter.ParseAsExpression <Func <TEntity, object> >(selectExpression, "entity"); if (sortType.OrderType == OrderType.Descending) { query.OrderByDescending(expression); } else { query.OrderByAscending(expression); } } #endregion 排序 var pageList = Store.GetPagedList(query); pageList = PagedListStyle(pageList); return(pageList); }