コード例 #1
0
        private Expression CheckNullOnFirstGroup(ExpressionParserPieceGroup group, Expression currentExpression)
        {
            var path            = string.Join(".", group.Pieces.Select(t => t.Name));
            var whereExpression = QueryableHelpers.CreateConditionExpression(group.Parameter.Type, path,
                                                                             ConditionOperators.NotEqual, null, QueryConvertStrategy.ConvertConstantToComparedPropertyOrField,
                                                                             parameter: group.Parameter, nullChecking: true);

            var whereBodyExpression = (whereExpression as LambdaExpression).Body;

            whereBodyExpression = Expression.Not(whereBodyExpression);



            var        nullType         = currentExpression.Type;
            Expression ifTrueExpression = null;

            if (QueryableHelpers.IsGenericEnumerable(nullType))
            {
                var listType = typeof(List <>).MakeGenericType(nullType.GenericTypeArguments.First());
                ifTrueExpression = Expression.New(listType);
            }
            else
            {
                ifTrueExpression = Expression.Default(nullType);
            }

            return(Expression.Condition(whereBodyExpression, ifTrueExpression, currentExpression, currentExpression.Type));
        }
コード例 #2
0
ファイル: ExpressionParser.cs プロジェクト: vebin/DynamicLinq
        public void Parse()
        {
            Pieces.Clear();

            var pathPieces = Path.Split('.').ToList();
            var param      = Parameter;
            ExpressionParserPiece parent = null;

            pathPieces.ForEach(pp =>
            {
                var memberExpression = Expression.PropertyOrField(param, pp);
                var current          = new ExpressionParserPiece
                {
                    Type = memberExpression.Type,
                    IsGenericEnumerable = QueryableHelpers.IsGenericEnumerable(memberExpression),
                    EnumerableType      = memberExpression.Type.GenericTypeArguments.FirstOrDefault(),
                    Parent = parent,
                    Name   = pp
                };

                Pieces.Add(current);

                // for next iteration.
                param  = Expression.Parameter(current.IsGenericEnumerable ? current.EnumerableType : current.Type);
                parent = current;
            });
        }
コード例 #3
0
        private static Expression CheckNullOnEnumerableParent(ExpressionParserPieceGroup group, ExpressionParserPieceGroup parent, Expression parentExpression, bool shouldSkipLast)
        {
            string path = null;

            if (shouldSkipLast)
            {
                path = string.Join(".", group.Pieces.Take(group.Pieces.Count - 1).Select(t => t.Name));
            }
            else
            {
                path = string.Join(".", group.Pieces.Select(t => t.Name));
            }

            if (!string.IsNullOrEmpty(path))
            {
                var whereExpression = QueryableHelpers.CreateConditionExpression(group.Parameter.Type, path,
                                                                                 ConditionOperators.NotEqual, null, QueryConvertStrategy.ConvertConstantToComparedPropertyOrField,
                                                                                 parameter: group.Parameter, nullChecking: true);

                //public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
                parentExpression = Expression.Call(typeof(Enumerable), "Where",
                                                   new Type[] { parent.GroupEnumerableType() },
                                                   parentExpression, whereExpression);
            }

            return(parentExpression);
        }
コード例 #4
0
        protected virtual Expression <Func <TEntity, bool> > CreateEntityExpression(TEntity entity)
        {
            var objectKey  = GetBsonIdProperty();
            var constant   = objectKey.GetValue(entity);
            var expression = QueryableHelpers.CreateConditionExpression <TEntity>(objectKey.Name,
                                                                                  DynamicLinq.ConditionOperators.Equal, constant, DynamicLinq.QueryConvertStrategy.LeaveAsIs);

            return(expression);
        }
コード例 #5
0
        public Task <TEntity> GetAsync(object key, CancellationToken cancellationToken = default(CancellationToken))
        {
            var keyProp    = GetBsonIdProperty();
            var expression = QueryableHelpers.CreateConditionExpression <TEntity>(keyProp.Name,
                                                                                  DynamicLinq.ConditionOperators.Equal, key, DynamicLinq.QueryConvertStrategy.LeaveAsIs);
            var result = Collection.Find(expression).FirstOrDefaultAsync();

            return(result);
        }
コード例 #6
0
        public void TestInheritanceOfListAsGenericEnumerableType()
        {
            var shouldBeTrue = QueryableHelpers.IsGenericEnumerable(typeof(ListOfFoo));

            Assert.IsTrue(shouldBeTrue);
            var type = QueryableHelpers.GetTypeOfEnumerable(typeof(ListOfFoo), true);

            Assert.IsTrue(type == typeof(Foo));
        }
コード例 #7
0
ファイル: SelectBuilder.cs プロジェクト: incoplex/DynamicLinq
        public virtual IQueryable Build()
        {
            if (Empty)
            {
                throw new Exception("No select specified, please specify at least one select path");
            }

            var partsTuple = Parts.Select(t => (selectType: t.SelectType, propertyName: t.PropertyName, path: t.Path, selectCollectionHandling: t.SelectCollectionHandling)).ToList();

            return(QueryableHelpers.Select(Query, partsTuple, DestinationType, nullChecking: IsNullCheckingEnabled));
        }
コード例 #8
0
        public virtual IQueryable Build()
        {
            var query = Query;

            Sorts.ForEach(sort =>
            {
                query = QueryableHelpers.CreateOrderByExpression(query, sort.Path, sort.Direction, sort.Append);
            });

            return(query);
        }
コード例 #9
0
        private IQueryable <TEntity> GetEntitiesByNamePatternInternal <TEntity>(string namePattern)
            where TEntity : class, IEntityWithName
        {
            if (string.IsNullOrWhiteSpace(namePattern))
            {
                return(QueryableHelpers.Empty <TEntity>());
            }

            string[] pattern = SplitNameInternal(namePattern);

            return(this.context.Set <TEntity>().Where(
                       item =>
                       !string.IsNullOrWhiteSpace(item.Name) &&
                       IsMatchNameInternal(pattern, item.Name)));
        }
コード例 #10
0
ファイル: WhereBuilder.cs プロジェクト: vebin/DynamicLinq
        protected virtual Expression BuildConditionExpression(ParameterExpression parameter, WhereBuilderCondition filter)
        {
            var ret = QueryableHelpers.CreateConditionExpression(
                parameter.Type,
                filter.Path,
                filter.ConditionOperator,
                filter.Value,
                filter.ConvertStrategy,
                filter.CollectionHandling,
                parameter: parameter,
                nullChecking: IsNullCheckingEnabled,
                stringComparision: filter.StringComparisation
                );

            return(ret);
        }
コード例 #11
0
ファイル: HelpersTests.cs プロジェクト: vebin/DynamicLinq
        public void TestCreateFilterExpression()
        {
            var authors = new List <Author>()
            {
                new Author
                {
                    Id        = 1,
                    FirstName = "David",
                    LastName  = "Lebee",
                    Posts     = new List <Post>
                    {
                        new Post
                        {
                            Id       = 1,
                            AuthorId = 1,
                            Title    = "Match",
                            Content  = "ABC",
                            Comments = new List <Comment>()
                            {
                                new Comment()
                                {
                                    Id          = 1,
                                    DisplayName = "John Doe",
                                    CommentText = "!@#$!@#!@#",
                                    Email       = "*****@*****.**"
                                }
                            }
                        },
                        new Post
                        {
                            Id       = 2,
                            AuthorId = 1,
                            Title    = "Match",
                            Content  = "ABC",
                            Comments = new List <Comment>()
                        }
                    }
                },
                new Author
                {
                    Id        = 2,
                    FirstName = "Chuck",
                    LastName  = "Norris",
                    Posts     = new List <Post>
                    {
                        new Post
                        {
                            Id       = 3,
                            AuthorId = 2,
                            Title    = "Match",
                            Content  = "ASD",
                            Comments = new List <Comment>()
                        },
                        new Post
                        {
                            Id       = 4,
                            AuthorId = 2,
                            Title    = "DontMatch",
                            Content  = "ASD",
                            Comments = new List <Comment>()
                        }
                    }
                }
            };

            // the query.
            var query = authors.AsQueryable();

            var allExpression  = QueryableHelpers.CreateConditionExpression <Author>("Posts.Title", ConditionOperators.Equal, "Match", QueryConvertStrategy.ConvertConstantToComparedPropertyOrField, QueryCollectionHandling.All);
            var anyExpression  = QueryableHelpers.CreateConditionExpression <Author>("Posts.Title", ConditionOperators.Equal, "Match", QueryConvertStrategy.ConvertConstantToComparedPropertyOrField, QueryCollectionHandling.Any);
            var anyExpression2 = QueryableHelpers.CreateConditionExpression <Author>("Posts.Comments.Email", ConditionOperators.Equal, "*****@*****.**", QueryConvertStrategy.ConvertConstantToComparedPropertyOrField, QueryCollectionHandling.Any);

            Assert.AreEqual(1, query.Count(allExpression));
            Assert.AreEqual(2, query.Count(anyExpression));
            Assert.AreEqual(1, query.Count(anyExpression2));
        }
コード例 #12
0
 public static IQueryable <TEntity> QueryAnnotation <TEntity>(
     [NotNull] this IQueryable <TEntity> source,
     [NotNull] QueryAnnotationBase annotation)
     where TEntity : class
 => QueryableHelpers.CreateQuery(source, s => s.QueryAnnotation(annotation));
コード例 #13
0
 public static IQueryable GroupBy(this IQueryable query, Type type, string path)
 => QueryableHelpers.GroupBy(query, type, path);
コード例 #14
0
 // group by
 public static IQueryable GroupBy <T>(this IQueryable <T> query, string path)
 => QueryableHelpers.GroupBy(query, typeof(T), path);
コード例 #15
0
        public void Resolve()
        {
            Result = null;

            // parse the expression.
            if (!Parser.IsParsed)
            {
                Parser.Parse();
            }

            // group the piece by common parameters
            var groups = Parser.GroupBySharedParameters();

            Expression currentExpression = null;

            foreach (var group in groups.Reversed())
            {
                var isLastGroup = groups.IndexOf(group) == groups.Count - 1;

                if (currentExpression == null)
                {
                    var groupExpression       = CompileGroup(group, NullChecking);
                    var groupExpressionLambda = Expression.Lambda(groupExpression, group.Parameter);

                    if (group.Parent == null)
                    {
                        currentExpression = groupExpression;
                        if (NullChecking != false)
                        {
                            currentExpression = CheckNullOnFirstGroup(group, currentExpression);
                        }

                        currentExpression = Expression.Lambda(currentExpression, group.Parameter);
                        continue;
                    }

                    var parent           = group.Parent;
                    var parentExpression = CompileGroup(parent, NullChecking);

                    // check null with where.
                    var isSelectMany = CollectionHandling == SelectCollectionHandling.Flatten && QueryableHelpers.IsGenericEnumerable(groupExpression);
                    if (NullChecking != false)
                    {
                        parentExpression = CheckNullOnEnumerableParent(group, parent, parentExpression, isLastGroup && !isSelectMany);
                    }

                    // the select expression.
                    if (isSelectMany)
                    {
                        var selectType       = parent.GroupEnumerableType();
                        var selectExpression = Expression.Call(typeof(Enumerable), "SelectMany",
                                                               new Type[] { selectType, groupExpression.Type.GenericTypeArguments.First() },
                                                               parentExpression, groupExpressionLambda);
                        currentExpression = selectExpression;
                    }
                    else
                    {
                        var selectType       = parent.GroupEnumerableType();
                        var selectExpression = Expression.Call(typeof(Enumerable), "Select",
                                                               new Type[] { selectType, groupExpression.Type },
                                                               parentExpression, groupExpressionLambda);
                        currentExpression = selectExpression;
                    }
                }
                else
                {
                    if (group.Parent == null)
                    {
                        if (NullChecking != false)
                        {
                            currentExpression = CheckNullOnFirstGroup(group, currentExpression);
                        }

                        currentExpression = Expression.Lambda(currentExpression, group.Parameter);
                        continue;
                    }

                    var parent           = group.Parent;
                    var parentExpression = CompileGroup(parent, NullChecking);
                    var selectType       = parent.GroupEnumerableType();

                    bool isSelectMany = CollectionHandling == SelectCollectionHandling.Flatten && QueryableHelpers.IsGenericEnumerable(currentExpression);
                    if (NullChecking != false)
                    {
                        parentExpression = CheckNullOnEnumerableParent(group, parent, parentExpression, isLastGroup && !isSelectMany);
                    }

                    if (isSelectMany)
                    {
                        var currentExpressionLambda = Expression.Lambda(currentExpression, group.Parameter);
                        currentExpression = Expression.Call(typeof(Enumerable), "SelectMany",
                                                            new Type[] { selectType, currentExpression.Type.GenericTypeArguments.First() },
                                                            parentExpression, currentExpressionLambda);
                    }
                    else
                    {
                        var currentExpressionLambda = Expression.Lambda(currentExpression, group.Parameter);
                        currentExpression = Expression.Call(typeof(Enumerable), "Select",
                                                            new Type[] { selectType, currentExpression.Type },
                                                            parentExpression, currentExpressionLambda);
                    }
                }
            }

            Result = currentExpression;
        }
コード例 #16
0
 public static IQueryable <TEntity> FromSql <TEntity>(
     [NotNull] this IQueryable <TEntity> source,
     [NotNull] string sql,
     [NotNull] params object[] parameters)
     where TEntity : class
 => QueryableHelpers.CreateQuery(source, s => s.FromSql(sql, parameters));
コード例 #17
0
 public static IQueryable <TEntity> UseRelationalNullSemantics <TEntity>(
     [NotNull] this IQueryable <TEntity> source)
     where TEntity : class
 => QueryableHelpers.CreateQuery(source, s => s.UseRelationalNullSemantics());