/// <summary> /// 获取分页信息,不使用Mapper /// </summary> /// <typeparam name="TEntityOrView"></typeparam> /// <param name="query"></param> /// <param name="pagedInputDto"></param> /// <returns></returns> public static async Task <MyPagedResult <TEntityOrView> > GetPageEntityOrViewAsync <TEntityOrView>(this IQueryable <TEntityOrView> query, PagedInputDto pagedInputDto) where TEntityOrView : class { query = EntityFrameworkQueryableExtensions.AsNoTracking <TEntityOrView>(query); //排序 if (!string.IsNullOrEmpty(pagedInputDto.Order)) { List <string> strList = pagedInputDto.Order.Split(new char[1] { ',' }).ToList(); for (int i = 0; i < strList.Count; i++) { query = ((i != 0) ? ((!strList[i].ToLower().Contains("desc")) ? DynamicQueryable.OrderBy <TEntityOrView>(query, pagedInputDto.Order, Array.Empty <object>()) : DynamicQueryable.ThenByDescending <TEntityOrView>(query, pagedInputDto.Order, Array.Empty <object>())) : ((!strList[i].ToLower().Contains("desc")) ? DynamicQueryable.OrderBy <TEntityOrView>(query, pagedInputDto.Order, Array.Empty <object>()) : DynamicQueryable.OrderByDescending <TEntityOrView>(query, pagedInputDto.Order, Array.Empty <object>()))); } } if (pagedInputDto.Filter != null) { string text = pagedInputDto.Filter.ToWhere(); object[] array = pagedInputDto.Filter.paramValues.ToArray(); query = DynamicQueryable.Where <TEntityOrView>(query, text, array); } IQueryable <TEntityOrView> queryable = query.Skip(pagedInputDto.SkipCount).Take(pagedInputDto.PageSize); List <TEntityOrView> dataList = await EntityFrameworkQueryableExtensions.ToListAsync <TEntityOrView>(queryable, default(CancellationToken)); MyPagedResult <TEntityOrView> obj = new MyPagedResult <TEntityOrView>(); obj.PageSize = pagedInputDto.PageSize; obj.PageIndex = pagedInputDto.PageIndex; obj.DataList = dataList; obj.RowCount = query.Count(); return(obj); }
/// <summary> /// 多字段排序 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Sour"></param> /// <param name="SortExpression"></param> /// <param name="values"></param> /// <returns></returns> public static IQueryable <T> OrderBy <T>(this IQueryable <T> Sour, string SortExpression, params object[] values) { if (Sour == null) { throw new ArgumentException("操作对象为null"); } return(DynamicQueryable.OrderBy(Sour, SortExpression, values)); }
/// <summary> /// 排序 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query"></param> /// <param name="ordering">排序字符串,如:OrderBy("id desc,name ase")</param> /// <param name="values"></param> /// <returns></returns> public static IQueryable <T> OrderBy <T>(this IQueryable <T> query, string ordering, params object[] values) { if (query == null) { throw new ArgumentNullException("query"); } return(DynamicQueryable.OrderBy(query, ordering, values)); }
public virtual IQueryable <TEntity> GetMany(string where1, object[] whereParameters, Expression <Func <TEntity, bool> > where2, string orderBy, int totalNumber) { IQueryable <TEntity> queryable = DynamicQueryable.Where <TEntity>(this.Selector, where1, whereParameters); if (where2 != null) { queryable = queryable.Where(where2); } return(DynamicQueryable.OrderBy <TEntity>(queryable, orderBy, new object[0]).Take(totalNumber)); }
public static IQueryable <T> OrderBy <T>(this IQueryable <T> source, string sortExpression) { if (source == null) { throw new ArgumentNullException(nameof(source), "source is null."); } if (string.IsNullOrEmpty(sortExpression)) { throw new ArgumentException("sortExpression is null or empty.", nameof(sortExpression)); } return(DynamicQueryable.OrderBy(source, sortExpression.Replace("__", "."))); }
public virtual IQueryable <TEntity> GetMany(string where, object[] whereParameters, string orderBy) { IQueryable <TEntity> result; if (orderBy != null) { result = DynamicQueryable.OrderBy <TEntity>(DynamicQueryable.Where <TEntity>(this.Selector, where, whereParameters), orderBy, new object[0]); } else { result = DynamicQueryable.Where <TEntity>(this.Selector, where, whereParameters); } return(result); }
public void OrderBy_Exceptions() { //Arrange var testList = User.GenerateSampleModels(100, allowNullableProfiles: true); var qry = testList.AsQueryable(); //Act Assert.Throws <ParseException>(() => qry.OrderBy("Bad=3")); Assert.Throws <ParseException>(() => qry.Where("Id=123")); Assert.Throws <ArgumentNullException>(() => DynamicQueryable.OrderBy(null, "Id")); Assert.Throws <ArgumentNullException>(() => qry.OrderBy(null)); Assert.Throws <ArgumentException>(() => qry.OrderBy("")); Assert.Throws <ArgumentException>(() => qry.OrderBy(" ")); }
public static IQueryable <T> OrderBy <T>(this IQueryable <T> source, string sortExpression) { if (source == null) { return(source); } if (string.IsNullOrEmpty(sortExpression)) { return(source); } return(DynamicQueryable.OrderBy(source, sortExpression)); }
/// <summary> /// 带mapper /// </summary> /// <typeparam name="TEntityOrView"></typeparam> /// <typeparam name="TDto"></typeparam> /// <param name="query"></param> /// <param name="pagedInputDto"></param> /// <param name="configurationProvider"></param> /// <returns></returns> public static async Task <MyPagedResult <TDto> > GetPageAsync <TEntityOrView, TDto>(this IQueryable <TEntityOrView> query, PagedInputDto pagedInputDto) where TEntityOrView : class where TDto : class { query = EntityFrameworkQueryableExtensions.AsNoTracking <TEntityOrView>(query); //排序 if (!string.IsNullOrEmpty(pagedInputDto.Order)) { List <string> strList = pagedInputDto.Order.Split(new char[1] { ',' }).ToList(); for (int i = 0; i < strList.Count; i++) { query = ((i != 0) ? ((!strList[i].ToLower().Contains("desc")) ? DynamicQueryable.OrderBy <TEntityOrView>(query, pagedInputDto.Order, Array.Empty <object>()) : DynamicQueryable.ThenByDescending <TEntityOrView>(query, pagedInputDto.Order, Array.Empty <object>())) : ((!strList[i].ToLower().Contains("desc")) ? DynamicQueryable.OrderBy <TEntityOrView>(query, pagedInputDto.Order, Array.Empty <object>()) : DynamicQueryable.OrderByDescending <TEntityOrView>(query, pagedInputDto.Order, Array.Empty <object>()))); } } //if (!string.IsNullOrEmpty(pagedInputDto.Order)) //{ // query = DynamicQueryable.OrderBy<TEntityOrView>(query, pagedInputDto.Order, Array.Empty<object>()); //} if (pagedInputDto.Filter != null) { string text = pagedInputDto.Filter.ToWhere(); object[] array = pagedInputDto.Filter.paramValues.ToArray(); query = DynamicQueryable.Where <TEntityOrView>(query, text, array); } IQueryable <TEntityOrView> queryable = query.Skip(pagedInputDto.SkipCount).Take(pagedInputDto.PageSize); IQueryable <TDto> queryable2; if (!string.IsNullOrEmpty(pagedInputDto.Select)) { queryable2 = DynamicQueryable.Select(queryable, pagedInputDto.Select, Array.Empty <object>()).Cast <TDto>(); } else { queryable2 = Extensions.ProjectTo <TDto>(queryable, (AutoMapper.IConfigurationProvider)pagedInputDto.configurationProvider, Array.Empty <Expression <Func <TDto, object> > >()); } List <TDto> dataList = await EntityFrameworkQueryableExtensions.ToListAsync <TDto>(queryable2, default(CancellationToken)); MyPagedResult <TDto> obj = new MyPagedResult <TDto>(); obj.PageSize = pagedInputDto.PageSize; obj.PageIndex = pagedInputDto.PageIndex; obj.DataList = dataList; obj.RowCount = query.Count(); return(obj); }
public PagedList(IQueryable <T> oSource, int intPageIndex, int intPageSize, string sidx, string sord) { int num = oSource.Count <T>(); this.TotalCount = num; this.TotalPages = num / intPageSize; if (num % intPageSize > 0) { this.TotalPages++; } this.PageSize = intPageSize; this.PageIndex = intPageIndex; if (!string.IsNullOrEmpty(sidx)) { base.AddRange(DynamicQueryable.OrderBy <T>(oSource, sidx + " " + sord, new object[0]).Skip(intPageIndex * intPageSize).Take(intPageSize).ToList <T>()); } else { base.AddRange(oSource.Skip(intPageIndex * intPageSize).Take(intPageSize).ToList <T>()); } }
public static IQueryable <TEntity> SortByOptions <TEntity>(this IQueryable <TEntity> query, DxGridParams gridParams) { if (!gridParams.SortOptions.IsNullOrEmpty()) { JArray array = JArray.Parse(gridParams.SortOptions); List <string> sortOrders = new List <string>(); foreach (var item in array.ToList()) { var sortOptions = JObject.Parse(item.ToString()); var columnName = (string)sortOptions.SelectToken("selector"); var descending = (bool)sortOptions.SelectToken("desc"); if (descending) { columnName += " DESC"; } sortOrders.Add(columnName); } string sortOrdersStr = string.Join(",", sortOrders); query = System.Linq.Dynamic.DynamicQueryable.OrderBy(query, sortOrdersStr); } else { string columnName = string.Empty; PropertyInfo idPropertyInfo = query.ElementType.GetProperties().FirstOrDefault(x => x.Name.ToLower() == "id"); if (idPropertyInfo != null) { columnName = idPropertyInfo.Name; } else { columnName = query.ElementType.GetProperties()[0].Name; } query = DynamicQueryable.OrderBy(query, columnName); } return(query); }
public static PagedList <TEntity> TopagedList <TEntity, TKey>(this IQueryable <TEntity> source, EntityParam <TEntity, TKey> queryParam) where TEntity : EntityBase <TKey> { if (queryParam.Page <= 0) { queryParam.Page = 1; //throw new InvalidOperationException("起始记录数不能小于0"); } if (queryParam.PageSize <= 0) { queryParam.PageSize = 20; //throw new InvalidOperationException("每页记录数不能小于0"); } if (string.IsNullOrWhiteSpace(queryParam.Sort)) { queryParam.Sort = "Id"; } ObjectQuery <TEntity> query = source as ObjectQuery <TEntity>; if (query != null) { query.MergeOption = MergeOption.NoTracking; } using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.ReadUncommitted })) { var TotalRowCount = (source.Count <TEntity>()); source = DynamicQueryable.OrderBy <TEntity>(source, queryParam.Sort + " " + queryParam.SortType.ToString(), new object[0]); List <TEntity> data = source.Skip(queryParam.Page * queryParam.PageSize - queryParam.PageSize).Take(queryParam.PageSize).ToList <TEntity>(); scope.Complete(); var ret = new PagedList <TEntity>(data, queryParam.Page, queryParam.PageSize, TotalRowCount); return(ret); } }
public IQueryable <TEntity> OrderByData <TEntity>(IQueryable <TEntity> queryData, OrderByExpression orderByExpression) { string otype = orderByExpression.OrderByType == OrderByType.Asc ? "" : "desc"; string orderStr = orderByExpression.PropertyName + " " + otype; return(DynamicQueryable.OrderBy(queryData, orderStr)); //IOrderedQueryable<TEntity> result = null; //bool bFirst = true; //var item = orderByExpression; //while (item != null) //{ // Func<TEntity, DateTime> selectorDT = entity => // { // Type type = typeof(TEntity); // return (DateTime)type.GetProperty(item.PropertyName).GetValue(entity, null); // }; // Func<TEntity, string> selectorSTR = entity => // { // Type type = typeof(TEntity); // return Convert.ToString( type.GetProperty(item.PropertyName).GetValue(entity, null)); // }; // Func<TEntity, decimal> selectorDe = entity => // { // Type type = typeof(TEntity); // return Convert.ToDecimal(type.GetProperty(item.PropertyName).GetValue(entity, null)); // }; // dynamic selector = selectorSTR; // if (item.PropertyType == typeof(DateTime).ToString()) // { // selector = selectorDT; // } // else if (item.PropertyType == typeof(decimal).ToString()) // { // selector = selectorDe; // } // if (bFirst) // { // if (item.OrderByType == OrderByType.Asc) // { // result = queryData.OrderBy(entity => selector(entity)); // } // else // { // result = queryData.OrderByDescending(entity => selector(entity)); // } // bFirst = false; // } // else // { // if (item.OrderByType == OrderByType.Asc) // { // result = result.ThenBy(entity => selector(entity)); // } // else // { // result = result.ThenByDescending(entity => selector(entity)); // } // } // item = item.ThenOrderByExpression; //}; //return result.AsQueryable(); }
internal static IQueryable Deserialize(IQueryable query, IEnumerable <ServiceQueryPart> queryParts, QueryResolver queryResolver) { if (query == null) { throw Error.ArgumentNull("query"); } if (queryParts == null) { throw Error.ArgumentNull("queryParts"); } foreach (ServiceQueryPart part in queryParts) { switch (part.QueryOperator) { case "filter": try { query = DynamicQueryable.Where(query, part.Expression, queryResolver); } catch (ParseException e) { throw new ParseException( Error.Format(SRResources.ParseErrorInClause, "$filter", e.Message)); } break; case "orderby": try { query = DynamicQueryable.OrderBy(query, part.Expression, queryResolver); } catch (ParseException e) { throw new ParseException( Error.Format(SRResources.ParseErrorInClause, "$orderby", e.Message)); } break; case "skip": try { int skipCount = Convert.ToInt32(part.Expression, System.Globalization.CultureInfo.InvariantCulture); if (skipCount < 0) { throw new ParseException( Error.Format(SRResources.PositiveIntegerExpectedForODataQueryParameter, "$skip", part.Expression)); } query = DynamicQueryable.Skip(query, skipCount); } catch (FormatException e) { throw new ParseException( Error.Format(SRResources.ParseErrorInClause, "$skip", e.Message)); } break; case "top": try { int topCount = Convert.ToInt32(part.Expression, System.Globalization.CultureInfo.InvariantCulture); if (topCount < 0) { throw new ParseException( Error.Format(SRResources.PositiveIntegerExpectedForODataQueryParameter, "$top", part.Expression)); } query = DynamicQueryable.Take(query, topCount); } catch (FormatException e) { throw new ParseException( Error.Format(SRResources.ParseErrorInClause, "$top", e.Message)); } break; } } return(query); }
/// <summary> /// 排序 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query"></param> /// <param name="ordering">排序字段和类型</param> /// <param name="values"></param> /// <returns></returns> public static IQueryable <T> Order <T>(this IQueryable <T> query, string ordering, params object[] values) { return(DynamicQueryable.OrderBy(query, ordering, values)); }
public IQueryable OrderBy(IQueryable source, string ordering, params object[] values) { return(DynamicQueryable.OrderBy(source, ordering, values)); }
public DynamicQueryable BuildQuery( IQueryable queryable, IEnumerable <string> columns, NodeBase filter, IEnumerable <OrderItem> sort ) { var query = new DynamicQueryable(queryable); //Get all predicate expressions var predicateMembers = filter != null ? new DynamicProjectionPredicateMemberVisitor().Visit(filter) : new List <string>(); //Determine target of predicate (source or projection) var predicateTarget = predicateMembers.All(x => this.CompiledConfiguration.CompiledMembers.ContainsKey(x)) ? DynamicProjectionOperationTarget.Source : DynamicProjectionOperationTarget.Projection; //Determine target of sort (source or projection) var sortTarget = (sort ?? Enumerable.Empty <OrderItem>()) .All(x => CompiledConfiguration.CompiledMembers.ContainsKey(x.Expression)) ? DynamicProjectionOperationTarget.Source : DynamicProjectionOperationTarget.Projection; //Apply predicate on source if applicable if (filter != null && predicateTarget == DynamicProjectionOperationTarget.Source) { query = query.Where( new DynamicProjectionPredicateVisitor(this) .VisitLambda(filter)); } //Apply sort on source if applicable if (sort != null && sortTarget == DynamicProjectionOperationTarget.Source) { query = sort.Aggregate(query, (acc, next) => { var lambda = Expression.Lambda( CompiledConfiguration.CompiledMembers[next.Expression] .Source.SourceExpression, CompiledConfiguration.It); return(next.IsDescending ? query.OrderByDescending(lambda) : query.OrderBy(lambda)); }); } //Append predicate and sort columns to projection if needed var selectorColumns = columns ?? this.CompiledConfiguration.CompiledMembers.Select(x => x.Value.Member.MemberInfo?.Name); if (predicateTarget == DynamicProjectionOperationTarget.Projection) { selectorColumns = columns.Concat(predicateMembers); } if (sortTarget == DynamicProjectionOperationTarget.Projection) { selectorColumns = columns.Concat(sort.Select(x => x.Expression)); } selectorColumns = selectorColumns.Distinct().ToList(); //Apply selector query = query.Select(compiler.BuildSelector(selectorColumns)); //Apply predicate on projection if applicable if (filter != null && predicateTarget == DynamicProjectionOperationTarget.Projection) { query = query.Where( new ExpressionNodeVisitor() .VisitLambda(filter, configuration.ProjectedType)); } //Apply sort on projection if applicable if (sort != null && predicateTarget == DynamicProjectionOperationTarget.Projection) { query.OrderBy(sort); } return(query); }
public virtual IQueryable <TEntity> GetMany(string where, object[] whereParameters, string orderBy, int totalNumber) { return(DynamicQueryable.OrderBy <TEntity>(DynamicQueryable.Where <TEntity>(this.Selector, where, whereParameters), orderBy, new object[0]).Take(totalNumber)); }
public virtual IQueryable <TEntity> GetMany(Expression <Func <TEntity, bool> > where, string orderBy, int totalNumber) { return(DynamicQueryable.OrderBy <TEntity>(this.Selector.Where(where), orderBy, new object[0]).Take(totalNumber)); }