Beispiel #1
0
        public static void CopyFrom(this DbParameter @this, DbParameter from, string newParameterName)
        {
#if NETSTANDARD
            var fullName = @this.GetType().GetTypeInfo().FullName;
#else
            var fullName = @this.GetType().FullName;
#endif
            @this.DbType        = from.DbType;
            @this.Direction     = from.Direction;
            @this.IsNullable    = from.IsNullable;
            @this.ParameterName = newParameterName;
            @this.Size          = from.Size;

#if !EFCORE
            if (from is SqlParameter)
            {
                var fromSql = (SqlParameter)from;
                var toSql   = (SqlParameter)@this;

                toSql.SqlDbType   = fromSql.SqlDbType;
                toSql.UdtTypeName = fromSql.UdtTypeName;
            }
#endif

#if EF6
            if (fullName.Contains("Oracle") && from.GetType().GetProperty("OracleDbType") != null)
            {
                var property = from.GetType().GetProperty("OracleDbType");
                property.SetValue(@this, property.GetValue(from, null), new object[0]);
            }
#endif

            @this.Value = from.Value ?? DBNull.Value;
        }
        internal override void InitializeParameter(ProviderType type, DbParameter parameter, object value)
        {
            SqlType sqlType = (SqlType)type;

            if (sqlType.IsRuntimeOnlyType)
            {
                throw Error.BadParameterType(sqlType.GetClosestRuntimeType());
            }
            System.Data.SqlClient.SqlParameter sParameter = parameter as System.Data.SqlClient.SqlParameter;
            if (sParameter != null)
            {
                sParameter.SqlDbType = sqlType.SqlDbType;
                if (sqlType.HasPrecisionAndScale)
                {
                    sParameter.Precision = (byte)sqlType.Precision;
                    sParameter.Scale     = (byte)sqlType.Scale;
                }
            }
            else
            {
                PropertyInfo piSqlDbType = parameter.GetType().GetProperty("SqlDbType");
                if (piSqlDbType != null)
                {
                    piSqlDbType.SetValue(parameter, sqlType.SqlDbType, null);
                }
                if (sqlType.HasPrecisionAndScale)
                {
                    PropertyInfo piPrecision = parameter.GetType().GetProperty("Precision");
                    if (piPrecision != null)
                    {
                        piPrecision.SetValue(parameter, Convert.ChangeType(sqlType.Precision, piPrecision.PropertyType, CultureInfo.InvariantCulture), null);
                    }
                    PropertyInfo piScale = parameter.GetType().GetProperty("Scale");
                    if (piScale != null)
                    {
                        piScale.SetValue(parameter, Convert.ChangeType(sqlType.Scale, piScale.PropertyType, CultureInfo.InvariantCulture), null);
                    }
                }
            }
            parameter.Value = GetParameterValue(sqlType, value);

            int?determinedSize = DetermineParameterSize(sqlType, parameter);

            if (determinedSize.HasValue)
            {
                parameter.Size = determinedSize.Value;
            }
        }
Beispiel #3
0
        private DbParameter CloneParameter(DbParameter parameter)
        {
            try
            {
                if (parameter == null)
                {
                    return(null);
                }

                Type tDbParameter = parameter.GetType();

                DbParameter clone = Activator.CreateInstance(tDbParameter) as DbParameter;

                PropertyInfo[] props = tDbParameter.GetProperties(BindingFlags.Public | BindingFlags.SetField | BindingFlags.Instance);

                foreach (var p in props)
                {
                    p.SetValue(clone, p.GetValue(parameter));
                }


                return(clone);
            }
            catch (Exception)
            {
                return(parameter);
            }
        }
Beispiel #4
0
        /// <summary>
        /// 配置数据库命令参数
        /// </summary>
        /// <param name="name">参数名</param>
        /// <param name="value">参数值</param>
        /// <param name="dbParameterAttribute">参数特性</param>
        /// <param name="dbParameter">数据库命令参数</param>
        /// <returns>DbParameter</returns>
        internal static DbParameter ConfigureDbParameter(string name, object value, DbParameterAttribute dbParameterAttribute, DbParameter dbParameter)
        {
            // 设置参数方向
            dbParameter.ParameterName = name;
            dbParameter.Value         = value;
            dbParameter.Direction     = dbParameterAttribute.Direction;

            // 设置参数数据库类型
            if (dbParameterAttribute.DbType != null)
            {
                var type = dbParameterAttribute.DbType.GetType();
                if (type.IsEnum)
                {
                    // 处理通用 DbType 类型
                    if (typeof(DbType).IsAssignableFrom(type))
                    {
                        dbParameter.DbType = (DbType)dbParameterAttribute.DbType;
                    }

                    // 解决 Oracle 数据库游标类型参数
                    if (type.FullName.Equals("Oracle.ManagedDataAccess.Client.OracleDbType", StringComparison.OrdinalIgnoreCase))
                    {
                        dbParameter.GetType().GetProperty("OracleDbType")?.SetValue(dbParameter, dbParameterAttribute.DbType);
                    }
                }
            }

            // 设置大小,解决NVarchar,Varchar 问题
            if (dbParameterAttribute.Size > 0)
            {
                dbParameter.Size = dbParameterAttribute.Size;
            }

            return(dbParameter);
        }
Beispiel #5
0
        public List <DbParameter> ToDbParameters <TDbCommand>(TDbCommand cmd)
            where TDbCommand : DbCommand
        {
            List <DbParameter> toReturn = new List <DbParameter>();

            foreach (var item in this)
            {
                DbParameter toAdd = cmd.CreateParameter();
                toAdd.ParameterName           = item.ParameterName;
                toAdd.Size                    = item.Size;
                toAdd.SourceColumn            = item.SourceColumn;
                toAdd.Value                   = item.Value;
                toAdd.Direction               = item.Direction;
                toAdd.SourceColumnNullMapping = item.SourceColumnNullMapping;

                if (item.DbTypeEnum != null)
                {
                    var pInfoOfDbType = toAdd.GetType().GetProperties().FirstOrDefault(p => p.CanWrite && p.PropertyType == item.DbTypeEnum.GetType());

                    if (pInfoOfDbType != null)
                    {
                        pInfoOfDbType.SetValue(toAdd, item.DbTypeEnum);
                    }
                }

                toReturn.Add(toAdd);
            }

            return(toReturn);
        }
Beispiel #6
0
        public static void SetDbType(DbParameter param, string type)
        {
            if (param == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(type))
            {
                return;
            }

            var          paramType  = param.GetType();
            PropertyInfo dbTypeProp = null;

            if (!_DbTypePropertyCache.TryGetValue(paramType, out dbTypeProp))
            {
                dbTypeProp = paramType.GetProperties().Where(x => x.GetCustomAttributes(typeof(DbProviderSpecificTypePropertyAttribute), true).Any()).FirstOrDefault();
                _DbTypePropertyCache[paramType] = dbTypeProp;
            }
            if (dbTypeProp == null)
            {
                return;
            }

            try { dbTypeProp.SetValue(param, Enum.Parse(dbTypeProp.PropertyType, type)); }
            catch (ArgumentException) { }
        }
Beispiel #7
0
        protected virtual void SetDbType(DbParameter parameter, DBType dbType)
        {
            PropertyInfo property = parameter.GetType().GetProperty(typeof(DBType).Name);

            Debug.Assert(property != null);
            property.SetValue(parameter, dbType, null);
        }
Beispiel #8
0
        protected override void BuildCommand()
        {
            base.dbCommand.CommandText = this.spName;
            base.dbCommand.CommandType = CommandType.StoredProcedure;

            SPSchema schema = CacheManager.Instance.GetEntity <SPSchema, string>(owner.ConnectionName,
                                                                                 spName, TimeSpan.MaxValue,
                                                                                 (name) =>
            {
                return(owner.DbDriver.GetSpSchema(name));
            });

            ThrowExceptionUtil.ArgumentConditionTrue(schema != null, "tableName", "Can not find sp. Name:{0}".FormatWith(spName));

            DataAdapterParser dataAdapterParser = new DataAdapterParser(owner, dataAdapter);

            if (dataAdapter != null)
            {
                foreach (SPParameter spParameter in schema.ParameterList)
                {
                    DbParameter parameter = owner.DbDriver.CreateParameter();
                    parameter.ParameterName = spParameter.Name;
                    parameter.Direction     = spParameter.Direction;
                    //parameter.DbType = spParameter.DbType;
                    if (spParameter.DbType == "REF CURSOR")
                    {
                        IEntityProxy parameterProxy = EntityProxyManager.Instance.GetEntityProxyFromType(parameter.GetType());
                        if (parameter.GetType().Namespace == "System.Data.OracleClient")
                        {
                            parameterProxy.SetPropertyValue(parameter, "OracleType", 5);
                            //parameter.DbType = (DbType)5;
                        }
                        else
                        {
                            parameterProxy.SetPropertyValue(parameter, "OracleDbType", 0x79);
                        }
                    }

                    if (dataAdapter[spParameter.Name] != null)
                    {
                        parameter.Value = dataAdapter[spParameter.Name];
                    }
                    else
                    {
                        if (owner.DbDriver.DbTypeMap.ContainsKey(spParameter.DbType))
                        {
                            Type type = owner.DbDriver.DbTypeMap[spParameter.DbType];
                            parameter.Value = GetDefaultValue(type);

                            if (spParameter.Direction == ParameterDirection.InputOutput && spParameter.MaxLength > 0)
                            {
                                parameter.Size = spParameter.MaxLength * 2;
                            }
                        }
                    }

                    base.dbCommand.Parameters.Add(parameter);
                }
            }
        }
        private static object GetOracleParameterType(DbParameter dbParameter)
        {
            var parameterType = dbParameter.GetType();
            var typeProperty  = parameterType.GetProperty("OracleDbType") ??
                                throw new InvalidOperationException("Unable to find OracleDbType property");

            return(typeProperty.GetValue(dbParameter));
        }
Beispiel #10
0
 internal static void SetArrayBindSize(DbParameter parameter, int[] value)
 {
     if (ArrayBindSizeProperty == null)
     {
         ArrayBindSizeProperty = parameter.GetType().GetProperty("ArrayBindSize");
     }
     ArrayBindSizeProperty.SetValue(parameter, value);
 }
Beispiel #11
0
        internal override void InitializeParameter(SQLTYPE type, DbParameter parameter, object value)
        {
            var type2 = type;

            if (type2.IsRuntimeOnlyType)
            {
                throw Error.BadParameterType(type2.GetClosestRuntimeType());
            }
            SetDbType(parameter, type2.SqlDbType);
            if (type2.HasPrecisionAndScale)
            {
                Debug.Assert(type2.Precision > 0);
                Debug.Assert(type2.Scale >= 0);
                PropertyInfo info2 = parameter.GetType().GetProperty("Precision");
                if (info2 != null)
                {
                    info2.SetValue(parameter, Convert.ChangeType(type2.Precision, info2.PropertyType, CultureInfo.InvariantCulture), null);
                }
                PropertyInfo info3 = parameter.GetType().GetProperty("Scale");
                if (info3 != null)
                {
                    info3.SetValue(parameter, Convert.ChangeType(type2.Scale, info3.PropertyType, CultureInfo.InvariantCulture), null);
                }
            }
            //parameter.Size = 16;
#if DEBUG
            if (type2.IsString)
            {
                Debug.Assert(type2.Size > 0);
            }
#endif

            parameter.Value = GetParameterValue(type2, value);
            if (!((parameter.Direction == ParameterDirection.Input) && type2.IsFixedSize) && (parameter.Direction == ParameterDirection.Input))
            {
                return;
            }
            //Debug.Assert(type2.Size != null);
            int size = type2.Size.GetValueOrDefault();
            if ((size != SqlDataType <DBType> .NULL_VALUE && parameter.Size < size) || type2.IsLargeType)
            {
                parameter.Size = System.Math.Max(parameter.Size, size);
                Debug.Assert(parameter.Size >= 0);
            }
        }
Beispiel #12
0
        private static void AddRefCursorParameter(DbParameter parameter)
        {
            //we don't want a direct dependency, so we use reflection
            var fullName = parameter.GetType().FullName;

            if (fullName == "System.Data.OracleClient.OracleParameter")
            {
                var prop = parameter.GetType().GetProperty("OracleType");
                //OracleType.Cursor
                prop.SetValue(parameter, 5, null);
            }
            else if (fullName == "Oracle.DataAccess.Client.OracleParameter")
            {
                var prop = parameter.GetType().GetProperty("OracleDbType");
                //OracleDbType.RefCursor
                prop.SetValue(parameter, 121, null);
            }
        }
Beispiel #13
0
        public static string ConvertParameterValueToString(DbParameter Param, string NullString)
        {
            object Value = null;
            Type   t     = null;

            if (Param.GetType() == typeof(SqlParameter))
            {
                Value = Param.Value;
                t     = ConvertSqlDbTypeToDotNetType(((SqlParameter)Param).SqlDbType);
            }
            else if (Param.GetType() == typeof(OracleParameter))
            {
                Value = Param.Value;
                t     = ConvertOracleTypeToDotNetType(((OracleParameter)Param).OracleType);
            }

            return(ConvertValueToString(Value, t, NullString));
        }
Beispiel #14
0
        private void SetUdtTypeName(DbParameter parameter)
        {
            NonCapturingLazyInitializer.EnsureInitialized(
                ref _udtTypeNameSetter,
                parameter.GetType(),
                CreateUdtTypeNameAccessor);

            _udtTypeNameSetter(parameter, UdtTypeName);
        }
        protected DbParameter CreateParameter(DbCommand command)
        {
            DbParameter p      = command.CreateParameter();
            string      marker = SqlStatement.ConvertTypeToParameterMarker(p.GetType());

            p.ParameterName = ((marker + "p")
                               + command.Parameters.Count.ToString());
            command.Parameters.Add(p);
            return(p);
        }
Beispiel #16
0
        private void AddParaForOdpNet(string paraName, ParaType paraType, object value)
        {
            Assembly ass = GetAssembly();
            //工厂方法理解点
            DbParameter para = ass.CreateInstance("Oracle." + ManagedName + "DataAccess.Client.OracleParameter") as DbParameter;

            para.ParameterName = paraName;
            switch (paraType)
            {
            case ParaType.Cursor:
            case ParaType.OutPut:
                if (paraType == ParaType.Cursor)
                {
                    para.GetType().GetProperty("OracleDbType").SetValue(para, OracleDbType.RefCursor, null);
                }
                else
                {
                    para.DbType = DbType.String;
                    para.Size   = 4000;
                }
                para.Direction = ParameterDirection.Output;
                value          = DBNull.Value;
                break;

            case ParaType.ReturnValue:
                para.DbType    = DbType.Int32;
                para.Direction = ParameterDirection.ReturnValue;
                value          = DBNull.Value;
                break;

            case ParaType.CLOB:
            case ParaType.NCLOB:
                para.GetType().GetProperty("OracleDbType").SetValue(para, paraType == ParaType.CLOB ? OracleDbType.Clob : OracleDbType.NClob, null);
                para.Direction = ParameterDirection.Input;
                if (value != null)
                {
                    para.Value = value;
                }
                break;
            }
            Com.Parameters.Add(para);
        }
Beispiel #17
0
        private void SetUdtTypeName(DbParameter parameter)
        {
            NonCapturingLazyInitializer.EnsureInitialized(
                ref _udtTypeNameSetter,
                parameter.GetType(),
                CreateUdtTypeNameAccessor);

            if (parameter.Value != null && parameter.Value != DBNull.Value)
            {
                _udtTypeNameSetter(parameter, UdtTypeName);
            }
        }
        private DbParameter AddParameterWithValue(string parameterName, object value)
        {
            DbParameter p = _command.CreateParameter();

            p.ParameterName = parameterName;
            if (((value != null) && (value is Guid)) && p.GetType().FullName.Contains("Oracle"))
            {
                value = ((Guid)(value)).ToByteArray();
            }
            p.Value = value;
            _command.Parameters.Add(p);
            return(p);
        }
Beispiel #19
0
        // from sqlmetal
        private static DbParameter CreateParameter(DbCommand command, string name, SqlDbType dbType)
        {
            DbParameter parameter = command.CreateParameter();

            parameter.ParameterName = name;
            PropertyInfo property = parameter.GetType().GetProperty("SqlDbType");

            if (property != (PropertyInfo)null)
            {
                property.SetValue((object)parameter, (object)dbType, (object[])null);
            }
            return(parameter);
        }
Beispiel #20
0
        public static string GetInfo(DbParameter parameter)
        {
            StringBuilder builder = new StringBuilder();

            builder.AppendLine("DbParameter Info:");
            builder.AppendLine("------------------------------------------");
            builder.AppendLine($"GetType()     :{parameter.GetType()}");
            builder.AppendLine($"DbType        :{parameter.DbType}");
            builder.AppendLine($"Name          :{parameter.ParameterName}");
            builder.AppendLine($"Size          :{parameter.Size}");
            builder.AppendLine($"Value         :{parameter.Value}");
            builder.AppendLine("------------------------------------------");
            return(builder.ToString());
        }
Beispiel #21
0
        public void CanCreateSQLSpecificParameters()
        {
            using (TestResourceFile dbFile = new TestResourceFile(this, "Datastore.sdf"))
            {
                using (SmartClientDatabase database = DatabaseFactory.CreateDatabase() as SmartClientDatabase)
                {
                    DbParameter param = database.CreateParameter("@Price", SqlDbType.Money, 19, 12.95);
                    Assert.IsTrue(typeof(SqlCeParameter).IsAssignableFrom(param.GetType()));

                    SqlCeParameter sqlParam = (SqlCeParameter)param;
                    Assert.AreEqual(SqlDbType.Money, sqlParam.SqlDbType);
                }
            }
        }
Beispiel #22
0
        public static void CopyFrom(this DbParameter @this, DbParameter from)
        {
#if NETSTANDARD
            var fullName = @this.GetType().GetTypeInfo().FullName;
#else
            var fullName = @this.GetType().FullName;
#endif
            @this.DbType        = from.DbType;
            @this.Direction     = from.Direction;
            @this.IsNullable    = from.IsNullable;
            @this.ParameterName = from.ParameterName;
            @this.Size          = from.Size;

#if EF6
            if (fullName.Contains("Oracle") && from.GetType().GetProperty("OracleDbType") != null)
            {
                var property = from.GetType().GetProperty("OracleDbType");
                property.SetValue(@this, property.GetValue(from, null), new object[0]);
            }
#endif

            @this.Value = from.Value ?? DBNull.Value;
        }
    /// <summary>
    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    protected override void ConfigureParameter(DbParameter parameter)
    {
        var type = parameter.GetType();

        LazyInitializer.EnsureInitialized(ref _sqlDbTypeSetter, () => CreateSqlDbTypeAccessor(type));
        LazyInitializer.EnsureInitialized(ref _udtTypeNameSetter, () => CreateUdtTypeNameAccessor(type));

        if (parameter.Value == DBNull.Value)
        {
            parameter.Value = SqlBytes.Null;
        }

        _sqlDbTypeSetter(parameter, SqlDbType.Udt);
        _udtTypeNameSetter(parameter, _isGeography ? "geography" : "geometry");
    }
Beispiel #24
0
        /// <summary>
        /// Сопоставляем тип универсальный и типы оракла
        /// </summary>
        /// <param name="uniType"></param>
        private void MapOracleDbTypes(UniDbType uniType)
        {
            Dictionary <UniDbType, string> p;

            if (dictionaryMapType.TryGetValue(ProviderSetting.CurrentDBProvider, out p))
            {
                if (p.ContainsKey(uniType))
                {
                    string enumString = p[uniType];
                    // получаем  перечисление оракловое type
                    var enumType = Type.GetType($"{ProviderSetting.ConfigurationProvider.AssemblyNameSpace}.OracleDbType, {ProviderSetting.ConfigurationProvider.AssemblyName}");
                    // получаем оракловое значение
                    var enumValue = enumType.GetField(enumString).GetValue(null);
                    _parameter.GetType().GetProperty("OracleDbType").SetValue(_parameter, enumValue, null);
                }
            }
        }
Beispiel #25
0
        public static object SetGetValueAsObject
        (
            this DbParameter target
            , JToken jValue
        )
        {
            var type = target
                       .GetType();

            return
                (SetGetValueAsObject
                 (
                     target
                     , type
                     , jValue
                 ));
        }
Beispiel #26
0
        public void CanFindParameterByName()
        {
            CustomDbParameter parameter = new CustomDbParameter()
            {
                ParameterName = "@Param1", Value = _faker.Random.Int()
            };

            _builder.AddParameter(parameter);

            DbParameter param = _builder.GetParameter(parameter.ParameterName);

            Assert.IsNotNull(param);
            Assert.AreEqual(typeof(CustomDbParameter), param.GetType());
            Assert.That(_builder.Parameters.Count() == 1);
            Assert.That(param.ParameterName == parameter.ParameterName);
            Assert.That(param.Value == parameter.Value);
        }
        public static DbParameter ParamOut(string NomeParam, DbType Tipo, DbCommand cmd)
        {
            DbParameter ParametroOut = cmd.CreateParameter();

            ParametroOut.ParameterName = NomeParam;
            ParametroOut.DbType        = Tipo;
            ParametroOut.Direction     = ParameterDirection.Output;
            if (Tipo == DbType.String)
            {
                ParametroOut.Size = 2550;
            }
            if (Tipo == DbType.Object)
            {
                ParametroOut.GetType().GetProperty("OracleDbType").GetSetMethod().Invoke(ParametroOut, new object[] { 121 });
            }                                                                                                                                            // OracleDbType.RefCursor

            return(ParametroOut);
        }
        public static void SetOracleDevArtDbType(Assembly assembly, DbParameter dbParameter, object type)
        {
            if (_SetOracleDevArtDbType == null)
            {
                var dbtype          = assembly.GetType("Devart.Data.Oracle.OracleDbType");
                var dbParameterType = assembly.GetType("Devart.Data.Oracle.OracleParameter");
                var propertyInfo    = dbParameter.GetType().GetProperty("OracleDbType");

                var parameter             = Expression.Parameter(typeof(DbParameter));
                var parameterConvert      = Expression.Convert(parameter, dbParameterType);
                var parameterValue        = Expression.Parameter(typeof(object));
                var parameterValueConvert = Expression.Convert(parameterValue, dbtype);

                var property   = Expression.Property(parameterConvert, propertyInfo);
                var expression = Expression.Assign(property, parameterValueConvert);

                _SetOracleDevArtDbType = Expression.Lambda <Action <DbParameter, object> >(expression, parameter, parameterValue).Compile();
            }

            _SetOracleDevArtDbType(dbParameter, type);
        }
Beispiel #29
0
        /// <summary>
        /// 创建IDBDatabase
        /// </summary>
        /// <param name="providerFactory">表示一组方法,这些方法用于创建提供程序对数据源类的实现的实例</param>
        /// <returns>创建的IDBDatabase</returns>
        public static IDBDatabase CreateDatabase(DbProviderFactory providerFactory)
        {
            DBProvider dbProvider = new DBProvider();

            using (DbConnection cnn = providerFactory.CreateConnection())
                using (DbCommand cmd = providerFactory.CreateCommand())
                    using (DbCommandBuilder cmdBuilder = providerFactory.CreateCommandBuilder())
                        using (DbDataAdapter adapter = providerFactory.CreateDataAdapter())
                        {
                            DbParameter param = providerFactory.CreateParameter();
                            dbProvider.Connection     = cnn.GetType();
                            dbProvider.Command        = cmd.GetType();
                            dbProvider.Parameter      = param.GetType();
                            dbProvider.CommandBuilder = cmdBuilder.GetType();
                            dbProvider.DataAdapter    = adapter.GetType();
                        }

            IDBDatabase db = CreateDatabase(dbProvider);

            return(db);
        }
    private static object verifyBinaryDbTypeAndValue(DbCommand command, DbParameter param, byte[] value)
    {
        param.DbType = DbType.Binary;
        string typeName = command.GetType().AssemblyQualifiedName ?? "";

        if (typeName.Contains("Oracle.ManagedDataAccess"))
        {
            typeName = typeName.Replace("OracleCommand", "OracleDbType");
            Type?  enumType = Type.GetType(typeName);
            object?enumVal  = enumType != null?Enum.Parse(enumType, "Blob") : null;

            PropertyInfo?prop = param.GetType().GetRuntimeProperty("OracleDbType");
            prop?.SetValue(param, enumVal);
        }

        if (value != null)
        {
            param.Size = value.Length;
            return(value);
        }

        return(DBNull.Value);
    }