Esempio n. 1
0
        private BsonValue VisitValue(Expression expr, Expression left)
        {
            // check if left side is an enum and convert to string before return
            Func <Type, object, BsonValue> convert = (type, value) =>
            {
                var enumType = (left as UnaryExpression) == null ? null : (left as UnaryExpression).Operand.Type;

                if (enumType != null && enumType.GetTypeInfo().IsEnum)
                {
                    var str = Enum.GetName(enumType, value);
                    return(_mapper.Serialize(typeof(string), str, 0));
                }

                return(_mapper.Serialize(type, value, 0));
            };

            // its a constant; Eg: "fixed string"
            if (expr is ConstantExpression)
            {
                var value = (expr as ConstantExpression);

                return(convert(value.Type, value.Value));
            }
            else if (expr is MemberExpression && _parameters.Count > 0)
            {
                var mExpr  = (MemberExpression)expr;
                var mValue = this.VisitValue(mExpr.Expression, left);
                var value  = mValue.AsDocument[mExpr.Member.Name];

                return(convert(typeof(object), value));
            }
            else if (expr is ParameterExpression)
            {
                BsonValue result;
                if (_parameters.TryGetValue((ParameterExpression)expr, out result))
                {
                    return(result);
                }
            }

            // execute expression
            var objectMember = Expression.Convert(expr, typeof(object));
            var getterLambda = Expression.Lambda <Func <object> >(objectMember);
            var getter       = getterLambda.Compile();

            return(convert(typeof(object), getter()));
        }