Esempio n. 1
0
        /// <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);
        }
Esempio n. 2
0
        /// <summary>
        /// IQueryable{T}에 Between 조건을 추가합니다.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="expr"></param>
        /// <param name="lo"></param>
        /// <param name="hi"></param>
        /// <returns></returns>
        public static IQueryable <T> AddBetween <T>(this IQueryable <T> query, Expression <Func <T, object> > expr, object lo, object hi)
        {
            query.ShouldNotBeNull("query");

            var propertyName = ExpressionProcessor.FindMemberExpression(expr.Body);
            var betweenExpr  = IsBetweenExpression(propertyName);

            return(DynamicQueryable.Where(query, betweenExpr, lo, hi));
        }
Esempio n. 3
0
        /// <summary>
        /// 속성 < <paramref name="current"/> 인 질의를 추가합니다. (값이  <paramref name="current"/>보다 작다면, 이미 지나간 시간이라는 뜻)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="current"></param>
        /// <param name="expr"></param>
        /// <returns></returns>
        public static IQueryable <T> AddIsElapsed <T>(this IQueryable <T> query, DateTime current, Expression <Func <T, object> > expr)
        {
            query.ShouldNotBeNull("query");
            expr.ShouldNotBeNull("expr");

            var propertyName = ExpressionProcessor.FindMemberExpression(expr.Body);

            return(DynamicQueryable.Where(query, propertyName + " < @0", current));
        }
        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));
        }
Esempio n. 5
0
        /// <summary>
        /// 값이 null 이라면 "속성 IS NULL" 을, 값이 있다면, "속성 = value" 라는 질의를 추가합니다.
        /// (예: value가 'RealWeb'인 경우 Company='RealWeb', value가 null인 경우 Company IS NULL)
        /// </summary>
        public static IQueryable <T> AddEqOrNull <T>(this IQueryable <T> query, Expression <Func <T, object> > expr, object value)
        {
            query.ShouldNotBeNull("query");
            expr.ShouldNotBeNull("expr");

            var propertyName = ExpressionProcessor.FindMemberExpression(expr.Body);

            var exprString = (value != null) ? propertyName + " == @0" : propertyName + " == null";

            return(DynamicQueryable.Where(query, exprString, value));
        }
Esempio n. 6
0
        /// <summary>
        /// 지정된 속성이 지정된 값과 같거나, 속성 값이 NULL인 경우 (예: Name=:Name OR Name IS NULL)
        /// </summary>
        public static IQueryable <T> AddEqIncludeNull <T>(this IQueryable <T> query, Expression <Func <T, object> > expr, object value)
        {
            query.ShouldNotBeNull("query");
            expr.ShouldNotBeNull("expr");

            var proeprtyName = ExpressionProcessor.FindMemberExpression(expr.Body);

            var exprString = string.Format("{0}==@0 || {0} == null", proeprtyName);

            return(DynamicQueryable.Where(query, exprString, value));
        }
Esempio n. 7
0
        /// <summary>
        /// 지정한 속성 값이 NULL이면 True로 간주하는 Where 절을 추가한다.
        /// Explicit 하게 PropertyName = False 로 되어 있는 것을 제외한 True이거나 NULL 것은 True 로 간주한다.
        /// </summary>
        public static IQueryable <T> AddNullAsTrue <T>(this IQueryable <T> query, Expression <Func <T, object> > expr, bool?value)
        {
            var propertyName = ExpressionProcessor.FindMemberExpression(expr.Body);

            if (value.GetValueOrDefault(true) == false)
            {
                return(DynamicQueryable.Where(query, propertyName + " == @0", false));
            }

            return(AddEqIncludeNull(query, expr, true));
        }
Esempio n. 8
0
        /// <summary>
        /// IQueryable{T}에 InRange 조건을 추가합니다.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="value"></param>
        /// <param name="loExpr"></param>
        /// <param name="hiExpr"></param>
        /// <returns></returns>
        public static IQueryable <T> AddInRange <T>(this IQueryable <T> query, object value, Expression <Func <T, object> > loExpr,
                                                    Expression <Func <T, object> > hiExpr)
        {
            query.ShouldNotBeNull("query");

            var loPropertyName = ExpressionProcessor.FindMemberExpression(loExpr.Body);
            var hiPropertyName = ExpressionProcessor.FindMemberExpression(hiExpr.Body);
            var isInRangeExpr  = IsInRangeExpression(loPropertyName, hiPropertyName);

            return(DynamicQueryable.Where(query, isInRangeExpr, value));
        }
        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);
        }
Esempio n. 10
0
        public static IQueryable <T> Where <T>(this IQueryable <T> source, string predicate, params object[] args)
        {
            if (source == null)
            {
                return(source);
            }

            if (string.IsNullOrEmpty(predicate))
            {
                return(source);
            }

            return(DynamicQueryable.Where(source, predicate, args));
        }
        public void Where_Exceptions()
        {
            //Arrange
            var testList = User.GenerateSampleModels(100, allowNullableProfiles: true);
            var qry      = testList.AsQueryable();

            //Act
            Assert.Throws <ParseException>(() => qry.Where("Id"));
            Assert.Throws <ParseException>(() => qry.Where("Bad=3"));
            Assert.Throws <ParseException>(() => qry.Where("Id=123"));

            Assert.Throws <ArgumentNullException>(() => DynamicQueryable.Where(null, "Id=1"));
            Assert.Throws <ArgumentNullException>(() => qry.Where(null));
            Assert.Throws <ArgumentException>(() => qry.Where(""));
            Assert.Throws <ArgumentException>(() => qry.Where(" "));
        }
Esempio n. 12
0
        /// <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);
        }
Esempio n. 13
0
        /// <summary>
        /// LINQ에 Insensitive Like 검색을 위한 표현식을 추가합니다.
        /// </summary>
        public static IQueryable <T> AddInsensitiveLike <T>(this IQueryable <T> query, Expression <Func <T, string> > expr, string value,
                                                            MatchMode matchMode)
        {
            query.ShouldNotBeNull("query");
            expr.ShouldNotBeNull("expr");

            if (value.IsEmpty())
            {
                return(query);
            }

            matchMode = matchMode ?? MatchMode.Anywhere;

            var propertyName = ExpressionProcessor.FindMemberExpression(expr.Body);

            var exprString = string.Empty;

            if (matchMode == MatchMode.Anywhere)
            {
                exprString = string.Format("{0}.ToLower().Contains(@0)", propertyName);
            }
            else if (matchMode == MatchMode.Start)
            {
                exprString = string.Format("{0}.ToLower().StartsWith(@0)", propertyName);
            }
            else if (matchMode == MatchMode.End)
            {
                exprString = string.Format("{0}.ToLower().EndsWith(@0)", propertyName);
            }
            else if (matchMode == MatchMode.Exact)
            {
                exprString = string.Format("{0}.ToLower() == @0", propertyName);
            }

            if (exprString.IsNotWhiteSpace())
            {
                return(DynamicQueryable.Where(query, exprString, value.AsText().ToLower()));
            }

            return(query);
        }
 public virtual bool Any(string predicate, params object[] values)
 {
     return(DynamicQueryable.Where <TEntity>(this.Selector, predicate, values).Any <TEntity>());
 }
Esempio n. 15
0
 public static IQueryable <T> AddWhere <T>(this IQueryable <T> query, string expression, params object[] values)
 {
     return(DynamicQueryable.Where(query, expression, values));
 }
Esempio n. 16
0
        /// <summary>
        /// IQueryable{T}에 IsOverlap 조건을 추가합니다.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="period"></param>
        /// <param name="loExpr"></param>
        /// <param name="hiExpr"></param>
        /// <returns></returns>
        public static IQueryable <T> AddIsOverlap <T>(this IQueryable <T> query, ITimePeriod period, Expression <Func <T, object> > loExpr,
                                                      Expression <Func <T, object> > hiExpr)
        {
            period.ShouldNotBeNull("period");

            if (period.IsAnytime)
            {
                return(query);
            }

            loExpr.ShouldNotBeNull("loExpr");
            hiExpr.ShouldNotBeNull("hiExpr");

            var loPropertyName = ExpressionProcessor.FindMemberExpression(loExpr.Body);
            var hiPropertyName = ExpressionProcessor.FindMemberExpression(hiExpr.Body);

            var exprBuilder = new StringBuilder();

            if (period.HasStart && period.HasEnd)
            {
                exprBuilder
                .Append(IsInRangeExpression(loPropertyName, hiPropertyName)).Append(" || ")
                .Append(IsInRangeExpression(loPropertyName, hiPropertyName).Replace("@0", "@1")).Append(" || ")
                .Append(IsBetweenExpression(loPropertyName)).Append(" || ")
                .Append(IsBetweenExpression(hiPropertyName).Replace("@0", "@1"));

                var expr = exprBuilder.ToString();

                if (IsDebugEnabled)
                {
                    log.Debug("Overlap Expression=[{0}]", expr);
                }

                return(DynamicQueryable.Where(query, expr, period.Start, period.End));
            }
            if (period.HasStart)
            {
                exprBuilder
                .Append(IsInRangeExpression(loPropertyName, hiPropertyName)).Append(" || ")
                .Append(loPropertyName + " >= @0").Append(" || ")
                .Append(hiPropertyName + " >= @0");

                var expr = exprBuilder.ToString();

                if (IsDebugEnabled)
                {
                    log.Debug("Overlap Expression=[{0}]", expr);
                }

                return(DynamicQueryable.Where(query, expr, period.Start));
            }
            if (period.HasEnd)
            {
                exprBuilder
                .Append(IsInRangeExpression(loPropertyName, hiPropertyName)).Append(" || ")
                .Append(loPropertyName + " <= @0").Append(" || ")
                .Append(hiPropertyName + " <= @0");

                var expr = exprBuilder.ToString();

                if (IsDebugEnabled)
                {
                    log.Debug("Overlap Expression=[{0}]", expr);
                }

                return(DynamicQueryable.Where(query, expr, period.End));
            }

            throw new InvalidOperationException("기간이 Overlap되는지 판단하는 Criterion을 생성하기 위한 조건이 맞지 않습니다!!!");
        }
        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);
        }
Esempio n. 18
0
        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);
        }
Esempio n. 19
0
 public static IQueryable <T> Where <T>(this IQueryable <T> source, string predicate, params object[] values)
 {
     return((IQueryable <T>)DynamicQueryable.Where((IQueryable)source, predicate, values));
 }
 public IQueryable Where(IQueryable source, string predicate, params object[] values)
 {
     return(DynamicQueryable.Where(source, predicate, values));
 }
 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));
 }