protected virtual DbFunctionAggregate VisitFunctionAggregate(DbFunctionAggregate aggregate)
        {
            var result = aggregate;

            if (aggregate != null)
            {
                var newFunction  = VisitFunction(aggregate.Function);
                var newArguments = VisitExpressionList(aggregate.Arguments);

                Debug.Assert(newArguments.Count == 1, "Function aggregate had more than one argument?");

                if (!ReferenceEquals(aggregate.Function, newFunction)
                    ||
                    !ReferenceEquals(aggregate.Arguments, newArguments))
                {
                    if (aggregate.Distinct)
                    {
                        result = CqtBuilder.AggregateDistinct(newFunction, newArguments[0]);
                    }
                    else
                    {
                        result = CqtBuilder.Aggregate(newFunction, newArguments[0]);
                    }
                }
            }
            return(result);
        }
        public override DbExpression Visit(DbQuantifierExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var input     = VisitExpressionBindingEnterScope(expression.Input);
            var predicate = VisitExpression(expression.Predicate);

            ExitScope();

            if (!ReferenceEquals(expression.Input, input)
                ||
                !ReferenceEquals(expression.Predicate, predicate))
            {
                if (DbExpressionKind.All
                    == expression.ExpressionKind)
                {
                    result = CqtBuilder.All(input, predicate);
                }
                else
                {
                    Debug.Assert(
                        expression.ExpressionKind == DbExpressionKind.Any,
                        "DbQuantifierExpression had ExpressionKind other than All or Any?");
                    result = CqtBuilder.Any(input, predicate);
                }
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        protected virtual DbSortClause VisitSortClause(DbSortClause clause)
        {
            var result = clause;

            if (clause != null)
            {
                var newExpression = VisitExpression(clause.Expression);
                if (!ReferenceEquals(clause.Expression, newExpression))
                {
                    if (!string.IsNullOrEmpty(clause.Collation))
                    {
                        result = (clause.Ascending
                                      ? CqtBuilder.ToSortClause(newExpression, clause.Collation)
                                      : CqtBuilder.ToSortClauseDescending(newExpression, clause.Collation));
                    }
                    else
                    {
                        result = (clause.Ascending
                                      ? CqtBuilder.ToSortClause(newExpression)
                                      : CqtBuilder.ToSortClauseDescending(newExpression));
                    }
                }
            }
            return(result);
        }
        public override DbExpression Visit(DbGroupByExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newInput = VisitGroupExpressionBinding(expression.Input);

            EnterScope(newInput.Variable);
            var newKeys = VisitExpressionList(expression.Keys);

            ExitScope();
            EnterScope(newInput.GroupVariable);
            var newAggs = VisitList(expression.Aggregates, VisitAggregate);

            ExitScope();

            if (!ReferenceEquals(expression.Input, newInput)
                ||
                !ReferenceEquals(expression.Keys, newKeys)
                ||
                !ReferenceEquals(expression.Aggregates, newAggs))
            {
                var groupOutput =
                    TypeHelpers.GetEdmType <RowType>(TypeHelpers.GetEdmType <CollectionType>(expression.ResultType).TypeUsage);

                var boundKeys = groupOutput.Properties.Take(newKeys.Count).Select(p => p.Name).Zip(newKeys).ToList();
                var boundAggs = groupOutput.Properties.Skip(newKeys.Count).Select(p => p.Name).Zip(newAggs).ToList();

                result = CqtBuilder.GroupBy(newInput, boundKeys, boundAggs);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        protected virtual DbLambda VisitLambda(DbLambda lambda)
        {
            Check.NotNull(lambda, "lambda");

            var result     = lambda;
            var newFormals = VisitList(
                lambda.Variables, varRef =>
            {
                var newVarType = VisitTypeUsage(varRef.ResultType);
                if (!ReferenceEquals(varRef.ResultType, newVarType))
                {
                    return(CqtBuilder.Variable(newVarType, varRef.VariableName));
                }
                else
                {
                    return(varRef);
                }
            }
                );

            EnterScope(newFormals.ToArray()); // ToArray: Don't pass the List instance directly to OnEnterScope
            var newBody = VisitExpression(lambda.Body);

            ExitScope();

            if (!ReferenceEquals(lambda.Variables, newFormals)
                ||
                !ReferenceEquals(lambda.Body, newBody))
            {
                result = CqtBuilder.Lambda(newBody, newFormals);
            }
            return(result);
        }
        public override DbExpression Visit(DbNewInstanceExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result       = expression;
            var          newType      = VisitTypeUsage(expression.ResultType);
            var          newArguments = VisitExpressionList(expression.Arguments);
            var          unchanged    = (ReferenceEquals(expression.ResultType, newType) && ReferenceEquals(expression.Arguments, newArguments));

            if (expression.HasRelatedEntityReferences)
            {
                var newRefs = VisitList(expression.RelatedEntityReferences, VisitRelatedEntityRef);
                if (!unchanged
                    ||
                    !ReferenceEquals(expression.RelatedEntityReferences, newRefs))
                {
                    result = CqtBuilder.CreateNewEntityWithRelationshipsExpression((EntityType)newType.EdmType, newArguments, newRefs);
                }
            }
            else
            {
                if (!unchanged)
                {
                    result = CqtBuilder.New(newType, newArguments.ToArray());
                }
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbApplyExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newInput = VisitExpressionBindingEnterScope(expression.Input);
            var newApply = VisitExpressionBinding(expression.Apply);

            ExitScope();

            if (!ReferenceEquals(expression.Input, newInput)
                ||
                !ReferenceEquals(expression.Apply, newApply))
            {
                if (DbExpressionKind.CrossApply
                    == expression.ExpressionKind)
                {
                    result = CqtBuilder.CrossApply(newInput, newApply);
                }
                else
                {
                    Debug.Assert(
                        expression.ExpressionKind == DbExpressionKind.OuterApply,
                        "DbApplyExpression had ExpressionKind other than CrossApply or OuterApply?");
                    result = CqtBuilder.OuterApply(newInput, newApply);
                }
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbConstantExpression expression)
        {
            Check.NotNull(expression, "expression");

            // Note that it is only safe to call DbConstantExpression.GetValue because the call to
            // DbExpressionBuilder.Constant must clone immutable values (byte[]).
            return(VisitTerminal(expression, newType => CqtBuilder.Constant(newType, expression.GetValue())));
        }
        public override DbExpression Visit(DbIsNullExpression expression)
        {
            Check.NotNull(expression, "expression");

            return(VisitUnary(
                       expression,
                       exp =>
                       TypeSemantics.IsRowType(exp.ResultType)
                    ? CqtBuilder.CreateIsNullExpressionAllowingRowTypeArgument(exp)
                    : CqtBuilder.IsNull(exp)));
        }
        public override DbExpression Visit(DbPropertyExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result      = expression;
            var          newInstance = VisitExpression(expression.Instance);

            if (!ReferenceEquals(expression.Instance, newInstance))
            {
                result = CqtBuilder.Property(newInstance, expression.Property.Name);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        protected virtual DbExpressionBinding VisitExpressionBinding(DbExpressionBinding binding)
        {
            var result = binding;

            if (binding != null)
            {
                var newInput = VisitExpression(binding.Expression);
                if (!ReferenceEquals(binding.Expression, newInput))
                {
                    result = CqtBuilder.BindAs(newInput, binding.VariableName);
                    RebindVariable(binding.Variable, result.Variable);
                }
            }
            return(result);
        }
        public override DbExpression Visit(DbCrossJoinExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newInputs = VisitExpressionBindingList(expression.Inputs);

            if (!ReferenceEquals(expression.Inputs, newInputs))
            {
                result = CqtBuilder.CrossJoin(newInputs);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbScanExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newSet = VisitEntitySet(expression.Target);

            if (!ReferenceEquals(expression.Target, newSet))
            {
                result = CqtBuilder.Scan(newSet);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        protected virtual DbGroupAggregate VisitGroupAggregate(DbGroupAggregate aggregate)
        {
            var result = aggregate;

            if (aggregate != null)
            {
                var newArguments = VisitExpressionList(aggregate.Arguments);
                Debug.Assert(newArguments.Count == 1, "Group aggregate had more than one argument?");

                if (!ReferenceEquals(aggregate.Arguments, newArguments))
                {
                    result = CqtBuilder.GroupAggregate(newArguments[0]);
                }
            }
            return(result);
        }
        public override DbExpression Visit(DbLambdaExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result       = expression;
            var          newArguments = VisitExpressionList(expression.Arguments);
            var          newLambda    = VisitLambda(expression.Lambda);

            if (!ReferenceEquals(expression.Arguments, newArguments)
                ||
                !ReferenceEquals(expression.Lambda, newLambda))
            {
                result = CqtBuilder.Invoke(newLambda, newArguments);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbProjectExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var input      = VisitExpressionBindingEnterScope(expression.Input);
            var projection = VisitExpression(expression.Projection);

            ExitScope();
            if (!ReferenceEquals(expression.Input, input)
                ||
                !ReferenceEquals(expression.Projection, projection))
            {
                result = CqtBuilder.Project(input, projection);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbLimitExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newArgument = VisitExpression(expression.Argument);
            var newLimit    = VisitExpression(expression.Limit);

            if (!ReferenceEquals(expression.Argument, newArgument)
                ||
                !ReferenceEquals(expression.Limit, newLimit))
            {
                Debug.Assert(!expression.WithTies, "Limit.WithTies == true?");
                result = CqtBuilder.Limit(newArgument, newLimit);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbArithmeticExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result       = expression;
            var          newArguments = VisitExpressionList(expression.Arguments);

            if (!ReferenceEquals(expression.Arguments, newArguments))
            {
                switch (expression.ExpressionKind)
                {
                case DbExpressionKind.Divide:
                    result = CqtBuilder.Divide(newArguments[0], newArguments[1]);
                    break;

                case DbExpressionKind.Minus:
                    result = CqtBuilder.Minus(newArguments[0], newArguments[1]);
                    break;

                case DbExpressionKind.Modulo:
                    result = CqtBuilder.Modulo(newArguments[0], newArguments[1]);
                    break;

                case DbExpressionKind.Multiply:
                    result = CqtBuilder.Multiply(newArguments[0], newArguments[1]);
                    break;

                case DbExpressionKind.Plus:
                    result = CqtBuilder.Plus(newArguments[0], newArguments[1]);
                    break;

                case DbExpressionKind.UnaryMinus:
                    result = CqtBuilder.UnaryMinus(newArguments[0]);
                    break;

                default:
                    throw new NotSupportedException();
                }
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbSortExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newInput     = VisitExpressionBindingEnterScope(expression.Input);
            var newSortOrder = VisitSortOrder(expression.SortOrder);

            ExitScope();

            if (!ReferenceEquals(expression.Input, newInput)
                ||
                !ReferenceEquals(expression.SortOrder, newSortOrder))
            {
                result = CqtBuilder.Sort(newInput, newSortOrder);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbJoinExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newLeft  = VisitExpressionBinding(expression.Left);
            var newRight = VisitExpressionBinding(expression.Right);

            EnterScope(newLeft.Variable, newRight.Variable);
            var newCondition = VisitExpression(expression.JoinCondition);

            ExitScope();

            if (!ReferenceEquals(expression.Left, newLeft)
                ||
                !ReferenceEquals(expression.Right, newRight)
                ||
                !ReferenceEquals(expression.JoinCondition, newCondition))
            {
                if (DbExpressionKind.InnerJoin
                    == expression.ExpressionKind)
                {
                    result = CqtBuilder.InnerJoin(newLeft, newRight, newCondition);
                }
                else if (DbExpressionKind.LeftOuterJoin
                         == expression.ExpressionKind)
                {
                    result = CqtBuilder.LeftOuterJoin(newLeft, newRight, newCondition);
                }
                else
                {
                    Debug.Assert(
                        expression.ExpressionKind == DbExpressionKind.FullOuterJoin,
                        "DbJoinExpression had ExpressionKind other than InnerJoin, LeftOuterJoin or FullOuterJoin?");
                    result = CqtBuilder.FullOuterJoin(newLeft, newRight, newCondition);
                }
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        private DbRelatedEntityRef VisitRelatedEntityRef(DbRelatedEntityRef entityRef)
        {
            RelationshipEndMember newSource;
            RelationshipEndMember newTarget;

            VisitRelationshipEnds(entityRef.SourceEnd, entityRef.TargetEnd, out newSource, out newTarget);
            var newTargetRef = VisitExpression(entityRef.TargetEntityReference);

            if (!ReferenceEquals(entityRef.SourceEnd, newSource)
                ||
                !ReferenceEquals(entityRef.TargetEnd, newTarget)
                ||
                !ReferenceEquals(entityRef.TargetEntityReference, newTargetRef))
            {
                return(CqtBuilder.CreateRelatedEntityRef(newSource, newTarget, newTargetRef));
            }
            else
            {
                return(entityRef);
            }
        }
        public override DbExpression Visit(DbCaseExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newWhens = VisitExpressionList(expression.When);
            var newThens = VisitExpressionList(expression.Then);
            var newElse  = VisitExpression(expression.Else);

            if (!ReferenceEquals(expression.When, newWhens)
                ||
                !ReferenceEquals(expression.Then, newThens)
                ||
                !ReferenceEquals(expression.Else, newElse))
            {
                result = CqtBuilder.Case(newWhens, newThens, newElse);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbLikeExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var newArgument = VisitExpression(expression.Argument);
            var newPattern  = VisitExpression(expression.Pattern);
            var newEscape   = VisitExpression(expression.Escape);

            if (!ReferenceEquals(expression.Argument, newArgument)
                ||
                !ReferenceEquals(expression.Pattern, newPattern)
                ||
                !ReferenceEquals(expression.Escape, newEscape))
            {
                result = CqtBuilder.Like(newArgument, newPattern, newEscape);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbRelationshipNavigationExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            RelationshipEndMember newFrom;
            RelationshipEndMember newTo;

            VisitRelationshipEnds(expression.NavigateFrom, expression.NavigateTo, out newFrom, out newTo);
            var newNavSource = VisitExpression(expression.NavigationSource);

            if (!ReferenceEquals(expression.NavigateFrom, newFrom)
                ||
                !ReferenceEquals(expression.NavigateTo, newTo)
                ||
                !ReferenceEquals(expression.NavigationSource, newNavSource))
            {
                result = CqtBuilder.Navigate(newNavSource, newFrom, newTo);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbRefExpression expression)
        {
            Check.NotNull(expression, "expression");

            DbExpression result = expression;

            var targetType = (EntityType)TypeHelpers.GetEdmType <RefType>(expression.ResultType).ElementType;

            var newArgument = VisitExpression(expression.Argument);
            var newType     = (EntityType)VisitType(targetType);
            var newSet      = (EntitySet)VisitEntitySet(expression.EntitySet);

            if (!ReferenceEquals(expression.Argument, newArgument)
                ||
                !ReferenceEquals(targetType, newType)
                ||
                !ReferenceEquals(expression.EntitySet, newSet))
            {
                result = CqtBuilder.RefFromKey(newSet, newArgument, newType);
            }
            NotifyIfChanged(expression, result);
            return(result);
        }
        public override DbExpression Visit(DbParameterReferenceExpression expression)
        {
            Check.NotNull(expression, "expression");

            return(VisitTerminal(expression, newType => CqtBuilder.Parameter(newType, expression.ParameterName)));
        }