예제 #1
0
        protected override QueryConverter.ConversionMethod ChooseConversionMethod(Type fromType, Type toType)
        {
            Type nonNullableType = TypeSystem.GetNonNullableType(fromType);
            Type seqType         = TypeSystem.GetNonNullableType(toType);

            if ((fromType != toType) && (nonNullableType == seqType))
            {
                return(ConversionMethod.Lift);
            }
            if (!TypeSystem.IsSequenceType(nonNullableType) && !TypeSystem.IsSequenceType(seqType))
            {
                IProviderType type3             = this.typeProvider.From(nonNullableType);
                IProviderType type4             = this.typeProvider.From(seqType);
                bool          isRuntimeOnlyType = type3.IsRuntimeOnlyType;
                bool          flag2             = type4.IsRuntimeOnlyType;
                if (isRuntimeOnlyType || flag2)
                {
                    return(ConversionMethod.Treat);
                }

                //if (type3.IsNumeric && type4.IsNumeric)
                //    return ConversionMethod.Ignore;

                if (((nonNullableType != seqType) && (!type3.IsString || !type3.Equals(type4))) &&
                    (!nonNullableType.IsEnum && !seqType.IsEnum))
                {
                    return(ConversionMethod.Convert);
                }
            }
            return(ConversionMethod.Ignore);
        }
예제 #2
0
            internal override SqlExpression VisitTreat(SqlUnary t)
            {
                t.Operand = this.VisitExpression(t.Operand);
                Type treatType    = t.ClrType;
                Type originalType = model.GetMetaType(t.Operand.ClrType).InheritanceRoot.Type;

                // .NET nullability rules are that typeof(int)==typeof(int?). Let's be consistent with that:
                treatType    = TypeSystem.GetNonNullableType(treatType);
                originalType = TypeSystem.GetNonNullableType(originalType);

                if (treatType == originalType)
                {
                    return(t.Operand);
                }
                if (treatType.IsAssignableFrom(originalType))
                {
                    t.Operand.SetClrType(treatType);
                    return(t.Operand);
                }
                if (!treatType.IsAssignableFrom(originalType) && !originalType.IsAssignableFrom(treatType))
                {
                    if (!treatType.IsInterface && !originalType.IsInterface)
                    {                     // You can't tell when there's an interface involved.
                        // We statically know the TREAT will result in NULL.
                        return(sql.TypedLiteralNull(treatType, t.SourceExpression));
                    }
                }

                //return base.VisitTreat(t);
                return(t);
            }
예제 #3
0
파일: TypeSource.cs 프로젝트: zyj0021/ALinq
        // Methods
        internal static MetaType GetSourceMetaType(SqlNode node, MetaModel model)
        {
            Visitor visitor = new Visitor();

            visitor.Visit(node);
            Type nonNullableType = TypeSystem.GetNonNullableType(visitor.sourceType);

            return(model.GetMetaType(nonNullableType));
        }
예제 #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.Objects.ObjectParameter" /> class with the specified name and type.
 /// </summary>
 /// <param name="name">The parameter name. This name should not include the "@" parameter marker that is used in the Entity SQL statements, only the actual name. The first character of the expression must be a letter. Any successive characters in the expression must be either letters, numbers, or an underscore (_) character.</param>
 /// <param name="type">The common language runtime (CLR) type of the parameter.</param>
 /// <exception cref="T:System.ArgumentNullException">If the value of either argument is null.</exception>
 /// <exception cref="T:System.ArgumentOutOfRangeException">If the value of the name argument is invalid. Parameter names must start with a letter and can only contain letters, numbers, and underscores.</exception>
 public ObjectParameter(string name, Type type)
 {
     Check.NotNull <string>(name, nameof(name));
     Check.NotNull <Type>(type, nameof(type));
     if (!ObjectParameter.ValidateParameterName(name))
     {
         throw new ArgumentException(Strings.ObjectParameter_InvalidParameterName((object)name), nameof(name));
     }
     this._name         = name;
     this._type         = type;
     this._mappableType = TypeSystem.GetNonNullableType(this._type);
 }
예제 #5
0
 internal override SqlRow VisitRow(SqlRow row)
 {
     for (int i = 0, n = row.Columns.Count; i < n; i++)
     {
         SqlColumn     col  = row.Columns[i];
         SqlExpression expr = this.VisitExpression(col.Expression);
         if (expr != null)
         {
             if (TypeSystem.GetNonNullableType(col.ClrType) != TypeSystem.GetNonNullableType(expr.ClrType))
             {
                 throw Error.ColumnClrTypeDoesNotAgreeWithExpressionsClrType();
             }
         }
     }
     return(row);
 }
예제 #6
0
        // -------------------
        // Public Constructors
        // -------------------

        #region ObjectParameter (string, Type)

        /// <summary>
        /// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.Objects.ObjectParameter" /> class with the specified name and type.
        /// </summary>
        /// <param name="name">The parameter name. This name should not include the "@" parameter marker that is used in the Entity SQL statements, only the actual name. The first character of the expression must be a letter. Any successive characters in the expression must be either letters, numbers, or an underscore (_) character.</param>
        /// <param name="type">The common language runtime (CLR) type of the parameter.</param>
        /// <exception cref="T:System.ArgumentNullException">If the value of either argument is null.</exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException">If the value of the name argument is invalid. Parameter names must start with a letter and can only contain letters, numbers, and underscores.</exception>
        public ObjectParameter(string name, Type type)
        {
            Check.NotNull(name, "name");
            Check.NotNull(type, "type");

            if (!ValidateParameterName(name))
            {
                throw new ArgumentException(Strings.ObjectParameter_InvalidParameterName(name), "name");
            }

            _name = name;
            _type = type;

            // If the parameter type is Nullable<>, we need to extract out the underlying
            // Nullable<> type argument.
            _mappableType = TypeSystem.GetNonNullableType(_type);
        }
예제 #7
0
            private Expression Evaluate(Expression e)
            {
                Type type = e.Type;

                if (e.NodeType == ExpressionType.Convert)
                {
                    UnaryExpression unaryExpression = (UnaryExpression)e;
                    if (TypeSystem.GetNonNullableType(unaryExpression.Operand.Type) == TypeSystem.GetNonNullableType(type))
                    {
                        e = ((UnaryExpression)e).Operand;
                    }
                }
                if (e.NodeType == ExpressionType.Constant)
                {
                    if (e.Type != type)
                    {
                        if (TypeSystem.GetNonNullableType(e.Type) == TypeSystem.GetNonNullableType(type))
                        {
                            return(Expression.Constant(((ConstantExpression)e).Value, type));
                        }
                    }
                    else
                    {
                        return(e);
                    }
                }
                MemberExpression memberExpression = e as MemberExpression;

                if (memberExpression != null)
                {
                    ConstantExpression expression = memberExpression.Expression as ConstantExpression;
                    if (expression != null)
                    {
                        return(this.PostEval(Expression.Constant(memberExpression.Member.GetValue(expression.Value), type)));
                    }
                }
                if (type.IsValueType)
                {
                    e = Expression.Convert(e, typeof(object));
                }
                Expression <Func <object> > expression1 = Expression.Lambda <Func <object> >(e, new ParameterExpression[0]);
                Func <object> func = expression1.Compile();

                return(this.PostEval(Expression.Constant(func(), type)));
            }
예제 #8
0
        // Methods
        internal override SqlRow VisitRow(SqlRow row)
        {
            int num   = 0;
            int count = row.Columns.Count;

            while (num < count)
            {
                SqlColumn     column     = row.Columns[num];
                SqlExpression expression = this.VisitExpression(column.Expression);
                if ((expression != null) &&
                    (TypeSystem.GetNonNullableType(column.ClrType) != TypeSystem.GetNonNullableType(expression.ClrType)))
                {
                    throw Error.ColumnClrTypeDoesNotAgreeWithExpressionsClrType();
                }
                num++;
            }
            return(row);
        }
예제 #9
0
        static void Main(string[] args)
        {
            var provider  = new CnblogsQueryProvider();
            var queryable = new Query <Post>(provider);

            var query = from p in queryable
                        where p.Title.Contains("001") &&
                        p.Diggs >= 10 &&
                        p.Comments > 10 &&
                        p.Views > 10 &&
                        p.Comments < 20
                        select p;

            //var list = query.ToList();

            TypeSystem.GetNonNullableType(typeof(Post));

            Console.Read();
        }
예제 #10
0
        internal static bool TryDetermineCSpaceModelType(Type type, MetadataWorkspace workspace, out EdmType modelEdmType)
        {
            Debug.Assert(null != workspace);
            Type nonNullabelType = TypeSystem.GetNonNullableType(type);

            // make sure the workspace knows about T
            workspace.ImplicitLoadAssemblyForType(nonNullabelType, System.Reflection.Assembly.GetCallingAssembly());
            ObjectItemCollection objectItemCollection = (ObjectItemCollection)workspace.GetItemCollection(DataSpace.OSpace);
            EdmType objectEdmType;

            if (objectItemCollection.TryGetItem <EdmType>(nonNullabelType.FullName, out objectEdmType))
            {
                Map map;
                if (workspace.TryGetMap(objectEdmType, DataSpace.OCSpace, out map))
                {
                    ObjectTypeMapping objectMapping = (ObjectTypeMapping)map;
                    modelEdmType = objectMapping.EdmType;
                    return(true);
                }
            }
            modelEdmType = null;
            return(false);
        }
예제 #11
0
            internal override SqlExpression TranslateDateTimeBinary(SqlBinary bo)
            {
                bool asNullable      = TypeSystem.IsNullableType(bo.ClrType);
                var  nonNullableType = TypeSystem.GetNonNullableType(bo.Right.ClrType);
                var  nodeType        = bo.NodeType;

                if (nodeType != SqlNodeType.Add)
                {
                    if (nodeType != SqlNodeType.Sub)
                    {
                        return(bo);
                    }
                    if (nonNullableType == typeof(DateTime))
                    {
                        var clrType     = bo.ClrType;
                        var left        = bo.Left;
                        var right       = bo.Right;
                        var expression3 = new SqlVariable(typeof(void), null, "DAY", bo.SourceExpression);
                        var expression4 = new SqlVariable(typeof(void), null, "MILLISECOND", bo.SourceExpression);
                        var expr        = sql.FunctionCall(typeof(int), "DATEDIFF", new[] { expression3, right, left }, bo.SourceExpression);
                        var expression6 = sql.FunctionCall(typeof(DateTime), "DATEADD", new[] { expression3, expr, right }, bo.SourceExpression);
                        var expression7 = sql.FunctionCall(typeof(int), "DATEDIFF", new[] { expression4, expression6, left }, bo.SourceExpression);
                        var expression8 = sql.Multiply(sql.Add(new[] { sql.Multiply(sql.ConvertToBigint(expr), 0x5265c00L), expression7 }), 0x2710L);
                        return(sql.ConvertTo(clrType, expression8));
                    }
                    if (nonNullableType != typeof(TimeSpan))
                    {
                        return(bo);
                    }
                    return(CreateDateTimeFromDateAndTicks(bo.Left, sql.Unary(SqlNodeType.Negate, bo.Right, bo.SourceExpression), bo.SourceExpression, asNullable));
                }
                if (nonNullableType == typeof(TimeSpan))
                {
                    return(CreateDateTimeFromDateAndTicks(bo.Left, bo.Right, bo.SourceExpression, asNullable));
                }
                return(bo);
            }
예제 #12
0
        private static bool CanDbConvert(Type from, Type to)
        {
            @from = TypeSystem.GetNonNullableType(@from);
            to    = TypeSystem.GetNonNullableType(to);
            if (@from == to)
            {
                return(true);
            }
            if (to.IsAssignableFrom(@from))
            {
                return(true);
            }
            var tcTo   = Type.GetTypeCode(to);
            var tcFrom = Type.GetTypeCode(@from);

            switch (tcTo)
            {
#warning [FB] REFACTOR SQL Server specific
            case TypeCode.Int16: return(tcFrom == TypeCode.Byte || tcFrom == TypeCode.SByte);

            case TypeCode.Int32: return(tcFrom == TypeCode.Byte || tcFrom == TypeCode.SByte || tcFrom == TypeCode.Int16 || tcFrom == TypeCode.UInt16);

            case TypeCode.Int64: return(tcFrom == TypeCode.Byte || tcFrom == TypeCode.SByte || tcFrom == TypeCode.Int16 || tcFrom == TypeCode.UInt16 || tcFrom == TypeCode.Int32 || tcFrom == TypeCode.UInt32);

            case TypeCode.UInt16: return(tcFrom == TypeCode.Byte || tcFrom == TypeCode.SByte);

            case TypeCode.UInt32: return(tcFrom == TypeCode.Byte || tcFrom == TypeCode.SByte || tcFrom == TypeCode.Int16 || tcFrom == TypeCode.UInt16);

            case TypeCode.UInt64: return(tcFrom == TypeCode.Byte || tcFrom == TypeCode.SByte || tcFrom == TypeCode.Int16 || tcFrom == TypeCode.UInt16 || tcFrom == TypeCode.Int32 || tcFrom == TypeCode.UInt32);

            case TypeCode.Double: return(tcFrom == TypeCode.Single);

            case TypeCode.Decimal: return(tcFrom == TypeCode.Single || tcFrom == TypeCode.Double);
            }
            return(false);
        }
예제 #13
0
        internal override SqlExpression TranslateConvertStaticMethod(SqlMethodCall mc)
        {
            if (mc.Arguments.Count != 1)
            {
                return(null);
            }
            var    expr = mc.Arguments[0];
            Type   type;
            string funcName;

            switch (mc.Method.Name)
            {
            case "ToBoolean":
                type     = typeof(bool);
                funcName = "CBool";
                break;

            case "ToDecimal":
                type     = typeof(decimal);
                funcName = "CDec";
                break;

            case "ToByte":
                type     = typeof(byte);
                funcName = "CInt";
                break;

            case "ToChar":
                type     = typeof(char);
                funcName = "CStr";
                if (expr.SqlType.IsChar)
                {
                    TypeProvider.From(type, 1);
                }
                break;

            case "ToDateTime":
            {
                var nonNullableType = TypeSystem.GetNonNullableType(expr.ClrType);
                if ((nonNullableType != typeof(string)) && (nonNullableType != typeof(DateTime)))
                {
                    throw SqlClient.Error.ConvertToDateTimeOnlyForDateTimeOrString();
                }
                type     = typeof(DateTime);
                funcName = "CDate";
                break;
            }

            case "ToDouble":
                type     = typeof(double);
                funcName = "CDbl";
                break;

            case "ToInt16":
                type     = typeof(short);
                funcName = "CInt";
                break;

            case "ToInt32":
                type     = typeof(int);
                funcName = "CInt";
                break;

            case "ToInt64":
                type     = typeof(long);
                funcName = "CLng";
                break;

            case "ToSingle":
                type     = typeof(float);
                funcName = "CSng";
                break;

            case "ToString":
                type     = typeof(string);
                funcName = "CStr";
                break;

            case "ToSByte":
                type     = typeof(sbyte);
                funcName = "CByte";
                break;

            default:
                throw SqlClient.Error.MethodHasNoSupportConversionToSql(mc);
            }

            if ((TypeProvider.From(type) != expr.SqlType) || ((expr.ClrType == typeof(bool)) && (type == typeof(int))))
            {
                if (type != typeof(DateTime))
                {
                    return(ConvertTo(type, TypeProvider.From(typeof(decimal)), expr));
                }
                return(ConvertTo(type, expr));
            }

            if ((type != expr.ClrType) && (TypeSystem.GetNonNullableType(type) == TypeSystem.GetNonNullableType(expr.ClrType)))
            {
                return(new SqlLift(type, expr, expr.SourceExpression));
            }
            return(expr);
        }
예제 #14
0
        public static object ChangeType(object value, Type type)
        {
            if (value == null)
            {
                return(null);
            }

            MethodInfo mi;

#warning [FB] REFACTOR: TYPE OBTAINED FROM SQLCLIENT. WILL CAUSE CONFLICTS WHEN OTHER DBs ARE ADDED.
            Type toType   = TypeSystem.GetNonNullableType(type);
            Type fromType = value.GetType();
            if (toType.IsAssignableFrom(fromType))
            {
                return(value);
            }

            if (toType == typeof(Binary))
            {
                if (fromType == typeof(byte[]))
                {
                    return(new Binary((byte[])value));
                }
                else if (fromType == typeof(Guid))
                {
                    return(new Binary(((Guid)value).ToByteArray()));
                }
                else
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    byte[]          streamArray;
                    using (MemoryStream stream = new MemoryStream())
                    {
                        formatter.Serialize(stream, value);
                        streamArray = stream.ToArray();
                    }
                    return(new Binary(streamArray));
                }
            }
            else if (toType == typeof(byte[]))
            {
                if (fromType == typeof(Binary))
                {
                    return(((Binary)value).ToArray());
                }
                else if (fromType == typeof(Guid))
                {
                    return(((Guid)value).ToByteArray());
                }
                else
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    byte[]          returnValue;
                    using (MemoryStream stream = new MemoryStream())
                    {
                        formatter.Serialize(stream, value);
                        returnValue = stream.ToArray();
                    }
                    return(returnValue);
                }
            }
            else if (fromType == typeof(byte[]))
            {
                if (toType == typeof(Guid))
                {
                    return(new Guid((byte[])value));
                }
                else
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    object          returnValue;
                    using (MemoryStream stream = new MemoryStream((byte[])value))
                    {
                        returnValue = ChangeType(formatter.Deserialize(stream), toType);
                    }
                    return(returnValue);
                }
            }
            else if (fromType == typeof(Binary))
            {
                if (toType == typeof(Guid))
                {
                    return(new Guid(((Binary)value).ToArray()));
                }
                else
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    using (MemoryStream stream = new MemoryStream(((Binary)value).ToArray(), false))
                    {
                        return(ChangeType(formatter.Deserialize(stream), toType));
                    }
                }
            }
            else if (toType.IsEnum)
            {
                if (fromType == typeof(string))
                {
                    string text = ((string)value).Trim();
                    return(Enum.Parse(toType, text));
                }
                else
                {
                    return(Enum.ToObject(toType, Convert.ChangeType(value, Enum.GetUnderlyingType(toType), Globalization.CultureInfo.InvariantCulture)));
                }
            }
            else if (fromType.IsEnum)
            {
                if (toType == typeof(string))
                {
                    return(Enum.GetName(fromType, value));
                }
                else
                {
                    return(Convert.ChangeType(Convert.ChangeType(value,
                                                                 Enum.GetUnderlyingType(fromType),
                                                                 Globalization.CultureInfo.InvariantCulture),
                                              toType,
                                              Globalization.CultureInfo.InvariantCulture));
                }
            }
            else if (toType == typeof(TimeSpan))
            {
                if (fromType == typeof(string))
                {
                    return(TimeSpan.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture));
                }
                else if (fromType == typeof(DateTime))
                {
                    return(DateTime.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture).TimeOfDay);
                }
                else if (fromType == typeof(DateTimeOffset))
                {
                    return(DateTimeOffset.Parse(value.ToString(), Globalization.CultureInfo.InvariantCulture).TimeOfDay);
                }
                else
                {
                    return(new TimeSpan((long)Convert.ChangeType(value, typeof(long), Globalization.CultureInfo.InvariantCulture)));
                }
            }
            else if (fromType == typeof(TimeSpan))
            {
                if (toType == typeof(string))
                {
                    return(((TimeSpan)value).ToString("", Globalization.CultureInfo.InvariantCulture));
                }
                else if (toType == typeof(DateTime))
                {
                    DateTime dt = new DateTime();
                    return(dt.Add((TimeSpan)value));
                }
                else if (toType == typeof(DateTimeOffset))
                {
                    DateTimeOffset dto = new DateTimeOffset();
                    return(dto.Add((TimeSpan)value));
                }
                else
                {
                    return(Convert.ChangeType(((TimeSpan)value).Ticks, toType, Globalization.CultureInfo.InvariantCulture));
                }
            }
            else if (toType == typeof(DateTime) && fromType == typeof(DateTimeOffset))
            {
                return(((DateTimeOffset)value).DateTime);
            }
            else if (toType == typeof(DateTimeOffset) && fromType == typeof(DateTime))
            {
                return(new DateTimeOffset((DateTime)value));
            }
            else if (toType == typeof(string) && !(typeof(IConvertible).IsAssignableFrom(fromType)))
            {
                if (fromType == typeof(char[]))
                {
                    return(new String((char[])value));
                }
                else
                {
                    return(value.ToString());
                }
            }
            else if (fromType == typeof(string))
            {
                if (toType == typeof(Guid))
                {
                    return(new Guid((string)value));
                }
                else if (toType == typeof(char[]))
                {
                    return(((String)value).ToCharArray());
                }
                else if (toType == typeof(System.Xml.Linq.XDocument) && (string)value == string.Empty)
                {
                    return(new System.Xml.Linq.XDocument());
                }
                else if (!(typeof(IConvertible).IsAssignableFrom(toType)) &&
                         (mi = toType.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, StringArg, null)) != null)
                {
                    try
                    {
                        return(SecurityUtils.MethodInfoInvoke(mi, null, new object[] { value }));
                    }
                    catch (TargetInvocationException t)
                    {
                        throw t.GetBaseException();
                    }
                }
                else
                {
                    return(Convert.ChangeType(value, toType, Globalization.CultureInfo.InvariantCulture));
                }
            }
            else if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(IQueryable <>) &&
                     typeof(IEnumerable <>).MakeGenericType(toType.GetGenericArguments()[0]).IsAssignableFrom(fromType)
                     )
            {
                return(Queryable.AsQueryable((IEnumerable)value));
            }
            else
            {
                if (toType.IsGenericType && toType.GetGenericTypeDefinition() == typeof(DbId <,>))
                {
                    object dbIdObject = Activator.CreateInstance(toType, value);
                    return(dbIdObject);
                }
                else
                {
                    if (fromType.IsGenericType && fromType.GetGenericTypeDefinition() == typeof(DbId <,>))
                    {
                        return(value);
                    }
                    else
                    {
                        try
                        {
                            return(Convert.ChangeType(value, toType, Globalization.CultureInfo.InvariantCulture));
                        }
                        catch (InvalidCastException)
                        {
                            throw Error.CouldNotConvert(fromType, toType);
                        }
                    }
                }
            }
        }
예제 #15
0
        internal override SqlExpression VisitUnaryOperator(SqlUnary uo)
        {
            uo.Operand = this.VisitExpression(uo.Operand);
            if (uo.NodeType != SqlNodeType.Convert)
            {
                return(uo);
            }
            ProviderType oldSqlType = uo.Operand.SqlType;
            ProviderType newSqlType = uo.SqlType;
            Type         oldClrType = TypeSystem.GetNonNullableType(uo.Operand.ClrType);
            Type         newClrType = TypeSystem.GetNonNullableType(uo.ClrType);

            if (newClrType == typeof(char))
            {
                if (oldClrType == typeof(bool))
                {
                    throw Error.ConvertToCharFromBoolNotSupported();
                }

                if (oldSqlType.IsNumeric)
                {
                    // numeric --> char
                    return(sql.FunctionCall(uo.ClrType, "NCHAR", new SqlExpression[] { uo.Operand }, uo.SourceExpression));
                }

                if (StringConversionIsSafe(oldSqlType, newSqlType))
                {
                    if (StringConversionIsNeeded(oldSqlType, newSqlType))
                    {
                        // set the new size to the (potentially smaller) oldSqlType.Size
                        uo.SetSqlType(sql.TypeProvider.From(uo.ClrType, oldSqlType.HasSizeOrIsLarge ? oldSqlType.Size : (int?)null));
                    }
                }
                else
                {
                    throw Error.UnsafeStringConversion(oldSqlType.ToQueryString(), newSqlType.ToQueryString());
                }
            }
            else if (oldClrType == typeof(char) && (oldSqlType.IsChar || oldSqlType.IsString) && newSqlType.IsNumeric)
            {
                // char --> int
                return(sql.FunctionCall(newClrType, sql.TypeProvider.From(typeof(int)), "UNICODE", new SqlExpression[] { uo.Operand }, uo.SourceExpression));
            }
            else if (newClrType == typeof(string))
            {
                if (oldClrType == typeof(double))
                {
                    // use longer format if it was a double in the CLR expression
                    return(ConvertDoubleToString(uo.Operand, uo.ClrType));
                }
                if (oldClrType == typeof(bool))
                {
                    // use 'true' or 'false' if it was a bool in the CLR expression
                    return(ConvertBitToString(uo.Operand, uo.ClrType));
                }
                if (StringConversionIsSafe(oldSqlType, newSqlType))
                {
                    if (StringConversionIsNeeded(oldSqlType, newSqlType))
                    {
                        // set the new size to the (potentially smaller) oldSqlType.Size
                        uo.SetSqlType(sql.TypeProvider.From(uo.ClrType, oldSqlType.HasSizeOrIsLarge ? oldSqlType.Size : (int?)null));
                    }
                }
                else
                {
                    throw Error.UnsafeStringConversion(oldSqlType.ToQueryString(), newSqlType.ToQueryString());
                }
            }
            return(uo);
        }
예제 #16
0
        private string TransformToEqualValue(WhereParams whereParams)
        {
            if (whereParams.Value == null)
            {
                return(Constants.NullValueNotAnalyzed);
            }

            if (Equals(whereParams.Value, string.Empty))
            {
                return(Constants.EmptyStringNotAnalyzed);
            }

            var type = TypeSystem.GetNonNullableType(whereParams.Value.GetType());

            if (type == typeof(bool))
            {
                return((bool)whereParams.Value ? "true" : "false");
            }

            if (type == typeof(DateTime))
            {
                var val = (DateTime)whereParams.Value;
                var s   = val.GetDefaultRavenFormat();
                if (val.Kind == DateTimeKind.Utc)
                {
                    s += "Z";
                }
                return(s);
            }

            if (type == typeof(DateTimeOffset))
            {
                var val = (DateTimeOffset)whereParams.Value;
                return(val.UtcDateTime.GetDefaultRavenFormat(true));
            }

            if (type == typeof(decimal))
            {
                return(RavenQuery.Escape(((double)((decimal)whereParams.Value)).ToString(CultureInfo.InvariantCulture), false, false));
            }

            if (type == typeof(double))
            {
                return(RavenQuery.Escape(((double)(whereParams.Value)).ToString("r", CultureInfo.InvariantCulture), false, false));
            }

            var strValue = whereParams.Value as string;

            if (strValue != null)
            {
                strValue = RavenQuery.Escape(strValue,
                                             whereParams.AllowWildcards && whereParams.IsAnalyzed, true);

                return(whereParams.IsAnalyzed ? strValue : String.Concat("[[", strValue, "]]"));
            }

            if (whereParams.Value is ValueType)
            {
                var escaped = RavenQuery.Escape(Convert.ToString(whereParams.Value, CultureInfo.InvariantCulture),
                                                whereParams.AllowWildcards && whereParams.IsAnalyzed, true);

                return(escaped);
            }

            var value = whereParams.Value as RavenJToken;

            if (value != null)
            {
                var term = value.ToString(Formatting.None).Trim('"');

                switch (value.Type)
                {
                case JTokenType.Object:
                case JTokenType.Array:
                    return("[[" + RavenQuery.Escape(term, false, false) + "]]");

                default:
                    return(RavenQuery.Escape(term, false, false));
                }
            }

            throw new NotSupportedException();
        }
예제 #17
0
파일: DBConvert.cs 프로젝트: zyj0021/ALinq
        /// <summary>
        /// Changes the specified value to the specified type.
        /// </summary>
        /// <param name="value">The object to be converted.</param>
        /// <param name="type">The type to convert the object to.</param>
        /// <returns>An object that contains the converted value of the specified type.</returns>
        public static object ChangeType(object value, Type type)
        {
            object obj3;

            if (value == null)
            {
                return(null);
            }
            type = TypeSystem.GetNonNullableType(type);
            Type enumType = value.GetType();

            if (type.IsAssignableFrom(value.GetType()))
            {
                return(value);
            }
            if (type == typeof(Binary))
            {
                byte[] buffer;
                if (enumType == typeof(byte[]))
                {
                    return(new Binary((byte[])value));
                }
                if (enumType == typeof(Guid))
                {
                    var guid = (Guid)value;
                    return(new Binary(guid.ToByteArray()));
                }
                var formatter = new BinaryFormatter();
                using (var stream = new MemoryStream())
                {
                    formatter.Serialize(stream, value);
                    buffer = stream.ToArray();
                }
                return(new Binary(buffer));
            }
            if (type == typeof(byte[]))
            {
                if (enumType == typeof(Binary))
                {
                    return(((Binary)value).ToArray());
                }
                if (enumType == typeof(Guid))
                {
                    var guid2 = (Guid)value;
                    return(guid2.ToByteArray());
                }
                var formatter2 = new BinaryFormatter();
                using (var stream2 = new MemoryStream())
                {
                    formatter2.Serialize(stream2, value);
                    return(stream2.ToArray());
                }
            }
            if (enumType == typeof(byte[]))
            {
                if (type == typeof(Guid))
                {
                    return(new Guid((byte[])value));
                }
                var formatter3 = new BinaryFormatter();
                using (var stream3 = new MemoryStream((byte[])value))
                {
                    return(ChangeType(formatter3.Deserialize(stream3), type));
                }
            }
            if (enumType == typeof(Binary))
            {
                if (type == typeof(Guid))
                {
                    return(new Guid(((Binary)value).ToArray()));
                }
                var formatter4 = new BinaryFormatter();
                using (var stream4 = new MemoryStream(((Binary)value).ToArray(), false))
                {
                    return(ChangeType(formatter4.Deserialize(stream4), type));
                }
            }
            if (type.IsEnum)
            {
                if (enumType == typeof(string))
                {
                    string str = ((string)value).Trim();
                    return(Enum.Parse(type, str));
                }
                return(Enum.ToObject(type, Convert.ChangeType(value, Enum.GetUnderlyingType(type), CultureInfo.InvariantCulture)));
            }
            if (enumType.IsEnum)
            {
                if (type == typeof(string))
                {
                    //return Enum.GetName(enumType, value);
                    return(value.ToString());
                }
                return(Convert.ChangeType(Convert.ChangeType(value, Enum.GetUnderlyingType(enumType), CultureInfo.InvariantCulture), type, CultureInfo.InvariantCulture));
            }
            if (type == typeof(TimeSpan))
            {
                if (enumType == typeof(string))
                {
                    return(TimeSpan.Parse((string)value));
                }
                return(new TimeSpan((long)Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture)));
            }
            if (enumType == typeof(TimeSpan))
            {
                if (type == typeof(string))
                {
                    return(value.ToString());
                }
                var span = (TimeSpan)value;
                return(Convert.ChangeType(span.Ticks, type, CultureInfo.InvariantCulture));
            }
            if ((type == typeof(string)) && !typeof(IConvertible).IsAssignableFrom(enumType))
            {
                if (enumType == typeof(char[]))
                {
                    return(new string((char[])value));
                }
                return(value.ToString());
            }
            if (enumType == typeof(string))
            {
                MethodInfo info;
                if (type == typeof(Guid))
                {
                    return(new Guid((string)value));
                }
                if (type == typeof(char[]))
                {
                    return(((string)value).ToCharArray());
                }
                if ((type == typeof(XDocument)) && (((string)value) == string.Empty))
                {
                    return(new XDocument());
                }
                if (!typeof(IConvertible).IsAssignableFrom(type) && ((info = type.GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, null, StringArg, null)) != null))
                {
                    try
                    {
                        return(info.Invoke(null, new[] { value }));
                    }
                    catch (TargetInvocationException exception)
                    {
                        throw exception.GetBaseException();
                    }
                }
                return(Convert.ChangeType(value, type, CultureInfo.InvariantCulture));
            }
            if ((type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(IQueryable <>))) && typeof(IEnumerable <>).MakeGenericType(new Type[] { type.GetGenericArguments()[0] }).IsAssignableFrom(enumType))
            {
                return(((IEnumerable)value).AsQueryable());
            }
            try
            {
                obj3 = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
            }
            catch (InvalidCastException)
            {
                throw Error.CouldNotConvert(value.GetType(), type);
            }
            return(obj3);
        }
예제 #18
0
파일: TypeSource.cs 프로젝트: zyj0021/ALinq
            // Methods
            internal override SqlNode Visit(SqlNode node)
            {
                if (node == null)
                {
                    return(null);
                }
                sourceExpression = node as SqlExpression;
                if (sourceExpression != null)
                {
                    Type clrType = sourceExpression.ClrType;
                    for (UnwrapStack stack = UnwrapSequences; stack != null; stack = stack.Last)
                    {
                        if (stack.Unwrap)
                        {
                            clrType = TypeSystem.GetElementType(clrType);
                        }
                    }
                    sourceType = clrType;
                }
                if ((sourceType != null) && TypeSystem.GetNonNullableType(sourceType).IsValueType)
                {
                    return(node);
                }
                if ((sourceType != null) && TypeSystem.HasIEnumerable(sourceType))
                {
                    return(node);
                }
                switch (node.NodeType)
                {
                case SqlNodeType.ClientCase:
                case SqlNodeType.Convert:
                case SqlNodeType.DiscriminatedType:
                    return(node);

                case SqlNodeType.MethodCall:
                case SqlNodeType.Member:
                    return(node);

                case SqlNodeType.Link:
                    sourceType = ((SqlLink)node).RowType.Type;
                    return(node);

                case SqlNodeType.Element:
                case SqlNodeType.FunctionCall:
                    return(node);

                case SqlNodeType.ScalarSubSelect:
                case SqlNodeType.SearchedCase:
                    return(node);

                case SqlNodeType.New:
                    return(node);

                case SqlNodeType.Multiset:
                    return(node);

                case SqlNodeType.TypeCase:
                    sourceType = ((SqlTypeCase)node).RowType.Type;
                    return(node);

                case SqlNodeType.Value:
                {
                    SqlValue value2 = (SqlValue)node;
                    if (value2.Value != null)
                    {
                        sourceType = value2.Value.GetType();
                    }
                    return(node);
                }

                case SqlNodeType.SimpleCase:
                    return(node);

                case SqlNodeType.Table:
                    sourceType = ((SqlTable)node).RowType.Type;
                    return(node);
                }
                return(base.Visit(node));
            }
예제 #19
0
        public static object ChangeType(object value, Type type)
        {
            if (value == null)
            {
                return(null);
            }
            var nonNullableType = TypeSystem.GetNonNullableType(type);
            var type2           = value.GetType();

            if (nonNullableType.IsAssignableFrom(type2))
            {
                return(value);
            }
            Guid guid;

            if (nonNullableType == typeof(Binary))
            {
                if (type2 == typeof(byte[]))
                {
                    return(new Binary((byte[])value));
                }
                if (type2 == typeof(Guid))
                {
                    guid = (Guid)value;
                    return(new Binary(guid.ToByteArray()));
                }
                var binaryFormatter = new BinaryFormatter();
                var value2          = default(byte[]);
                using (var memoryStream = new MemoryStream()) {
                    binaryFormatter.Serialize(memoryStream, value);
                    value2 = memoryStream.ToArray();
                }
                return(new Binary(value2));
            }
            if (nonNullableType == typeof(byte[]))
            {
                if (type2 == typeof(Binary))
                {
                    return(((Binary)value).ToArray());
                }
                if (type2 == typeof(Guid))
                {
                    guid = (Guid)value;
                    return(guid.ToByteArray());
                }
                var binaryFormatter2 = new BinaryFormatter();
                using (var memoryStream2 = new MemoryStream()) {
                    binaryFormatter2.Serialize(memoryStream2, value);
                    return(memoryStream2.ToArray());
                }
            }
            if (type2 == typeof(byte[]))
            {
                if (nonNullableType == typeof(Guid))
                {
                    return(new Guid((byte[])value));
                }
                var binaryFormatter3 = new BinaryFormatter();
                using (var serializationStream = new MemoryStream((byte[])value)) {
                    return(ChangeType(binaryFormatter3.Deserialize(serializationStream), nonNullableType));
                }
            }
            if (type2 == typeof(Binary))
            {
                if (nonNullableType == typeof(Guid))
                {
                    return(new Guid(((Binary)value).ToArray()));
                }
                var binaryFormatter4 = new BinaryFormatter();
                using (var serializationStream2 = new MemoryStream(((Binary)value).ToArray(), false)) {
                    return(ChangeType(binaryFormatter4.Deserialize(serializationStream2), nonNullableType));
                }
            }
            if (nonNullableType.IsEnum)
            {
                if (type2 == typeof(string))
                {
                    var value3 = ((string)value).Trim();
                    return(Enum.Parse(nonNullableType, value3));
                }
                return(Enum.ToObject(nonNullableType, Convert.ChangeType(value, Enum.GetUnderlyingType(nonNullableType), CultureInfo.InvariantCulture)));
            }
            if (type2.IsEnum)
            {
                if (nonNullableType == typeof(string))
                {
                    return(Enum.GetName(type2, value));
                }
                return(Convert.ChangeType(Convert.ChangeType(value, Enum.GetUnderlyingType(type2), CultureInfo.InvariantCulture), nonNullableType, CultureInfo.InvariantCulture));
            }
            DateTimeOffset dateTimeOffset;

            if (nonNullableType == typeof(TimeSpan))
            {
                if (type2 == typeof(string))
                {
                    return(TimeSpan.Parse(value.ToString(), CultureInfo.InvariantCulture));
                }
                if (type2 == typeof(DateTime))
                {
                    return(DateTime.Parse(value.ToString(), CultureInfo.InvariantCulture).TimeOfDay);
                }
                if (type2 == typeof(DateTimeOffset))
                {
                    dateTimeOffset = DateTimeOffset.Parse(value.ToString(), CultureInfo.InvariantCulture);
                    return(dateTimeOffset.TimeOfDay);
                }
                return(new TimeSpan((long)Convert.ChangeType(value, typeof(long), CultureInfo.InvariantCulture)));
            }
            if (type2 == typeof(TimeSpan))
            {
                TimeSpan timeSpan;
                if (nonNullableType == typeof(string))
                {
                    timeSpan = (TimeSpan)value;
                    return(timeSpan.ToString("", CultureInfo.InvariantCulture));
                }
                if (nonNullableType == typeof(DateTime))
                {
                    return(default(DateTime).Add((TimeSpan)value));
                }
                if (nonNullableType == typeof(DateTimeOffset))
                {
                    return(default(DateTimeOffset).Add((TimeSpan)value));
                }
                timeSpan = (TimeSpan)value;
                return(Convert.ChangeType(timeSpan.Ticks, nonNullableType, CultureInfo.InvariantCulture));
            }
            if (nonNullableType == typeof(DateTime) && type2 == typeof(DateTimeOffset))
            {
                dateTimeOffset = (DateTimeOffset)value;
                return(dateTimeOffset.DateTime);
            }
            if (nonNullableType == typeof(DateTimeOffset) && type2 == typeof(DateTime))
            {
                return(new DateTimeOffset((DateTime)value));
            }
            if (nonNullableType == typeof(string) && !typeof(IConvertible).IsAssignableFrom(type2))
            {
                if (type2 == typeof(char[]))
                {
                    return(new string((char[])value));
                }
                return(value.ToString());
            }
            if (type2 == typeof(string))
            {
                if (nonNullableType == typeof(Guid))
                {
                    return(new Guid((string)value));
                }
                if (nonNullableType == typeof(char[]))
                {
                    return(((string)value).ToCharArray());
                }
                if (nonNullableType == typeof(XDocument) && (string)value == string.Empty)
                {
                    return(new XDocument());
                }
                MethodInfo method;
                if (!typeof(IConvertible).IsAssignableFrom(nonNullableType) && (method = nonNullableType.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, null, StringArg, null)) != null)
                {
                    try {
                        return(SecurityUtils.MethodInfoInvoke(method, null, new object[1]
                        {
                            value
                        }));
                    } catch (TargetInvocationException ex) {
                        throw ex.GetBaseException();
                    }
                }
                return(Convert.ChangeType(value, nonNullableType, CultureInfo.InvariantCulture));
            }
            if (!nonNullableType.IsGenericType || !(nonNullableType.GetGenericTypeDefinition() == typeof(IQueryable <>)) || !typeof(IEnumerable <>).MakeGenericType(nonNullableType.GetGenericArguments()[0]).IsAssignableFrom(type2))
            {
                try {
                    return(Convert.ChangeType(value, nonNullableType, CultureInfo.InvariantCulture));
                } catch (InvalidCastException) {
                    throw System.Data.Linq.Error.CouldNotConvert(type2, nonNullableType);
                }
            }
            return(((IEnumerable)value).AsQueryable());
        }