public static int UpdateEntityForLobColumn <T>(IClassMapper classMap, T entity, out IDictionary <string, object> dynamicParameters) where T : class { dynamicParameters = entity.ToDictionary(); var lobColumns = classMap.Properties.Where(p => p.LobType != LobType.None); if (lobColumns.Count() == 0) { return(0); } int success = 0; foreach (var lobColumn in lobColumns) { string lobColumnKey = lobColumn.PropertyInfo.Name; if (dynamicParameters.ContainsKey(lobColumnKey)) { var lobColumnValue = dynamicParameters[lobColumnKey]; dynamicParameters[lobColumnKey] = LobConverter.ConvertValue(lobColumnValue, lobColumn.LobType); success++; } } return(success); }
public static int UpdateDynamicParameterForLobColumn(IClassMapper classMap, IDictionary <string, object> dynamicParameters) { //自动转换clob 或者blob类型 var lobColumns = classMap.Properties.Where(p => p.LobType != LobType.None); if (lobColumns.Count() == 0) { return(0); } int success = 0; foreach (var lobColumn in lobColumns) { string lobColumnKey = lobColumn.PropertyInfo.Name; if (dynamicParameters.ContainsKey(lobColumnKey)) { var lobColumnValue = dynamicParameters[lobColumnKey]; dynamicParameters[lobColumnKey] = LobConverter.ConvertValue(lobColumnValue, lobColumn.LobType); success++; } } return(success); }
internal ExecuteSqlParamsContext UpdateInternal(object bindedObj = null, IDictionary <string, object> _PrimaryKeyValues = null, params string[] ignoreProperties) { var pd = pocoData; if (bindedObj != null)//自动绑定对象 { BindPropertiesExts.BindPropertiesFromForDb(trackedObject, bindedObj, pd, ignoreProperties); } var columns = UpdatedColumns(); object poco = trackedObject; //int defaultValue = 0; if (columns != null && !columns.Any()) { return(null); } var sb = new StringBuilder(); var index = 0; string paramPrefix = ""; var pkCols = pd.Properties.Where(p => p.IsPrimaryKey).ToList(); IDictionary <string, object> PrimaryKeyValues = new Dictionary <string, object>(); if (_PrimaryKeyValues != null && _PrimaryKeyValues.Count > 0) { PrimaryKeyValues = _PrimaryKeyValues; } else { if (pkCols == null || pkCols.Count == 0) { throw new ArgumentException("当前对象没有主键情况下,需要指定更新的主键值"); } else { var Properties = pd.Properties.Select(p => p.PropertyInfo);// poco.GetType().GetProperties(); foreach (var pk in pkCols) { string pName = pk.Name; string pColumnName = pk.Name;// pk.ColumnName; var o = Properties.FirstOrDefault(y => string.Equals(pName, y.Name, StringComparison.OrdinalIgnoreCase)); if (o != null) { var pValue = o.GetValue(poco, null); PrimaryKeyValues.Add(pColumnName, pValue); } } } } IDictionary <string, object> parameters = new Dictionary <string, object>(); var waitToUpdated = pd.Properties.Where(p => columns.Contains(p.ColumnName) || p.IsVersionColumn == true); foreach (var pocoColumn in waitToUpdated) { string properyName = pocoColumn.Name;//pocoColumn.ColumnName; // Don't update the primary key, but grab the value if we don't have it if (_PrimaryKeyValues == null && PrimaryKeyValues.ContainsKey(properyName)) { continue; } // Dont update result only columns if (pocoColumn.Ignored || pocoColumn.IsReadOnly || pocoColumn.IsPrimaryKey) { continue; } var colType = pocoColumn.PropertyInfo.PropertyType; object value = pocoColumn.PropertyInfo.GetValue(poco, null);// GetColumnValue(pd, poco, ProcessMapper); if (pocoColumn.IsVersionColumn) { if (colType == typeof(int) || colType == typeof(Int32)) { value = Convert.ToInt32(value) + 1; } else if (colType == typeof(long) || colType == typeof(Int64)) { value = Convert.ToInt64(value) + 1; } else if (colType == typeof(short) || colType == typeof(Int16)) { value = Convert.ToInt16(value) + 1; } } else { if (Snapshotter.GetAutoFilterEmptyValueColumnsWhenTrack()) { var defaultValueOfCol = ReflectionHelper.GetDefaultValueForType(colType); if (object.Equals(defaultValueOfCol, value))//过滤空值列 { continue; } } } // Build the sql if (index > 0) { sb.Append(", "); } //string paramName = paramPrefix + index.ToString();// pocoColumn.Name; string paramName = paramPrefix + properyName; sb.AppendFormat("{0} = {1}{2}", db.SqlGenerator.GetColumnName(pd, pocoColumn, false), db.SqlGenerator.Configuration.Dialect.ParameterPrefix, paramName); parameters.Add(paramName, value); index++; } if (columns != null && columns.Any() && sb.Length == 0) { throw new ArgumentException("There were no columns in the columns list that matched your table", "columns"); } var sql = string.Format("UPDATE {0} SET {1} WHERE {2}", db.SqlGenerator.GetTableName(pd), sb, BuildWhereSql(db, pd, PrimaryKeyValues, paramPrefix, ref index)); int temIndex = parameters.Count; foreach (var item in PrimaryKeyValues) { parameters.Add(paramPrefix + item.Key, item.Value); //parameters.Add(paramPrefix + temIndex, item.Value); temIndex++; } if (db.DatabaseType == DatabaseType.Oracle && LobConverter.Enable == true) { IDictionary <string, object> dictParameters = parameters; int convertCount = LobConverter.UpdateDynamicParameterForLobColumn(pd, dictParameters); if (convertCount > 0) { //return db.Execute(sql, dictParameters); return(new ExecuteSqlParamsContext(sql, dictParameters)); } else { //执行原始SQL //return db.Execute(sql, parameters); return(new ExecuteSqlParamsContext(sql, parameters)); } } else { //执行原始SQL //return db.Execute(sql, parameters); return(new ExecuteSqlParamsContext(sql, parameters)); } }
private DbConnectionMetaInfo MapToDatabseConfig(PureDataConfiguration config, IDatabaseConfig databaseConfig) { DbConnectionMetaInfo metaInfo = null; if (config != null && databaseConfig != null) { if (config.Settings != null) { var settings = config.Settings; databaseConfig.ParameterPrefix = settings.ParameterPrefix; databaseConfig.ParameterSuffix = settings.ParameterSuffix; databaseConfig.GlobalTablePrefix = settings.GlobalTablePrefix; databaseConfig.ExecuteTimeout = settings.ExecuteTimeout; databaseConfig.DefaultPageSize = settings.DefaultPageSize; databaseConfig.AutoDisposeConnection = settings.AutoDisposeConnection; databaseConfig.ValidateStopOnFirstFailure = settings.ValidateStopOnFirstFailure; databaseConfig.LoadMapperMode = settings.LoadMapperMode; databaseConfig.EnableDebug = settings.EnableDebug; databaseConfig.EnableIntercept = settings.EnableIntercept; databaseConfig.EnableLogError = settings.EnableLogError; databaseConfig.EnableOrmLog = settings.EnableOrmLog; databaseConfig.EnableInternalLog = settings.EnableInternalLog; databaseConfig.LogWithRawSql = settings.LogWithRawSql; databaseConfig.CategoryLogType = settings.CategoryLogType; if (!string.IsNullOrEmpty(settings.OrmLogsPath)) { databaseConfig.OrmLogsPath = settings.OrmLogsPath; } databaseConfig.MaxServerLogSize = settings.MaxServerLogSize; databaseConfig.EnableOrmCache = settings.EnableOrmCache; databaseConfig.CacheOrmTime = settings.CacheOrmTime; databaseConfig.CacheOrmSingleTime = settings.CacheOrmSingleTime; databaseConfig.OrmCacheCheckPeriod = settings.OrmCacheCheckPeriod; databaseConfig.EnableSqlMap = settings.EnableSqlMap; databaseConfig.NameSpacePrefix = settings.NameSpacePrefix; databaseConfig.FormatSql = settings.FormatSql; databaseConfig.IsWatchSqlMapFile = settings.IsWatchSqlMapFile; databaseConfig.WatchSqlMapInterval = settings.WatchSqlMapInterval; databaseConfig.AutoMigrate = settings.AutoMigrate; databaseConfig.AutoRemoveUnuseColumnInTable = settings.AutoRemoveUnuseColumnInTable; databaseConfig.CanUpdatedWhenTableExisted = settings.CanUpdatedWhenTableExisted; databaseConfig.EnableAutoMigrateLog = settings.EnableAutoMigrateLog; databaseConfig.EnableAutoMigrateDebug = settings.EnableAutoMigrateDebug; databaseConfig.AutoMigrateOnContainTable = settings.AutoMigrateOnContainTable; databaseConfig.AutoMigrateWithoutTable = settings.AutoMigrateWithoutTable; if (!string.IsNullOrEmpty(settings.GlobalIgnoreUpdatedColumns)) { databaseConfig.GlobalIgnoreUpdatedColumns = settings.GlobalIgnoreUpdatedColumns; } databaseConfig.EnableGlobalIgnoreUpdatedColumns = settings.EnableGlobalIgnoreUpdatedColumns; databaseConfig.AutoFilterEmptyValueColumnsWhenTrack = settings.AutoFilterEmptyValueColumnsWhenTrack; //代码生成设置 databaseConfig.EnableCodeGen = settings.EnableCodeGen; databaseConfig.CodeGenType = settings.CodeGenType; databaseConfig.CodeGenClassNameMode = settings.CodeGenClassNameMode; databaseConfig.CodeGenPropertyNameMode = settings.CodeGenPropertyNameMode; databaseConfig.CodeGenProjectName = settings.CodeGenProjectName; databaseConfig.CodeGenNameSpace = settings.CodeGenNameSpace; databaseConfig.CodeGenTableFilter = settings.CodeGenTableFilter; string _basePath = ""; //if (databaseConfig.EnableCodeGen) //{ string[] basePaths = settings.CodeGenBaseDirectory.Split(';'); if (basePaths.Length > 0) { foreach (var basePath in basePaths) { if (System.IO.Directory.Exists(basePath)) { _basePath = basePath; break; } } } if (_basePath == "") { string baseRootPath = System.IO.Path.Combine(PathHelper.GetBaseDirectory(), "generate"); //if (Directory.Exists(baseRootPath)) //{ // DirectoryInfo info = new DirectoryInfo(baseRootPath); // _basePath = info.Parent.FullName; //} _basePath = baseRootPath; } //} databaseConfig.CodeGenBaseDirectory = _basePath; //databaseConfig.EnableConnectionPool = settings.EnableConnectionPool; //databaseConfig.EnableLogConnectionPool = settings.EnableLogConnectionPool; //databaseConfig.MinIdle = settings.MinIdle; //databaseConfig.MaxIdle = settings.MaxIdle; //databaseConfig.InitialSize = settings.InitialSize; //databaseConfig.MaxWaitMillis = settings.MaxWaitMillis; //databaseConfig.MaxTotal = settings.MaxTotal; //databaseConfig.TimeBetweenEvictionRunsMillis = settings.TimeBetweenEvictionRunsMillis; //databaseConfig.MinEvictableIdleTimeMillis = settings.MinEvictableIdleTimeMillis; //databaseConfig.EnableRemoveAbandoned = settings.EnableRemoveAbandoned; //databaseConfig.RemoveAbandonedOnBorrow = settings.RemoveAbandonedOnBorrow; //databaseConfig.RemoveAbandonedOnMaintenance = settings.RemoveAbandonedOnMaintenance; //databaseConfig.RemoveAbandonedTimeout = settings.RemoveAbandonedTimeout; //databaseConfig.NumTestsPerEvictionRun = settings.NumTestsPerEvictionRun; //databaseConfig.SoftMinEvictableIdleTimeMillis = settings.SoftMinEvictableIdleTimeMillis; //databaseConfig.TestOnBorrow = settings.TestOnBorrow; //databaseConfig.TestOnCreate = settings.TestOnCreate; //databaseConfig.TestOnReturn = settings.TestOnReturn; //databaseConfig.TestWhileIdle = settings.TestWhileIdle; //databaseConfig.ValidationQuery = settings.ValidationQuery; databaseConfig.EnableLobConverter = settings.EnableLobConverter; databaseConfig.LobConverterClassName = settings.LobConverterClassName; if (databaseConfig.EnableLobConverter == true) { try { Type type = Type.GetType(databaseConfig.LobConverterClassName); if (type != null) { object obj = Activator.CreateInstance(type, true); LobConverter.Init((ILobParameterConverter)(obj), databaseConfig.EnableLobConverter); } else { Log("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName, new ArgumentException("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName), MessageType.Error); } } catch (Exception ex) { Log("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName, new ArgumentException("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName), MessageType.Error); throw new ArgumentException("没有找到相关ILobParameterConverter实现类,LobConverterClassName: " + databaseConfig.LobConverterClassName, ex); } } databaseConfig.BulkOperateClassName = settings.BulkOperateClassName; databaseConfig.EnableDefaultPropertySecurityValidate = settings.EnableDefaultPropertySecurityValidate; databaseConfig.PropertySecurityValidateClassName = settings.PropertySecurityValidateClassName; if (!string.IsNullOrEmpty(settings.BulkOperateClassName)) { try { Type type = Type.GetType(settings.BulkOperateClassName); if (type != null) { IBulkOperate obj = (IBulkOperate)Activator.CreateInstance(type, true); BulkOperateManage.Instance.Register(settings.BulkOperateClassName, obj); } else { Log("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName, new ArgumentException("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName), MessageType.Error); } } catch (Exception ex) { Log("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName, new ArgumentException("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName), MessageType.Error); throw new ArgumentException("没有找到相关IBulkOperate实现类,BulkOperateClassName: " + settings.BulkOperateClassName, ex); } } if (!string.IsNullOrEmpty(settings.PropertySecurityValidateClassName)) { try { Type type = Type.GetType(settings.PropertySecurityValidateClassName); if (type != null) { IPropertySecurityValidate obj = (IPropertySecurityValidate)Activator.CreateInstance(type, true); PropertySecurityValidateManage.Instance.Register(settings.PropertySecurityValidateClassName, obj); } else { Log("IPropertySecurityValidate 无法找到实现类, 将启用默认的安全校验器!"); } } catch (Exception ex) { Log("IPropertySecurityValidate 无法找到实现类, 将启用默认的安全校验器!"); // throw new ArgumentException("没有找到相关IBulkOperate实现类,PropertySecurityValidateClassName: " + settings.PropertySecurityValidateClassName, ex); } } } try { if (config.DataSources != null) { string ConnectionString = "", ProviderName = ""; databaseConfig.DataSources = config.DataSources; foreach (var item in config.DataSources) { if (item.IsMaster == true)//是否主数据库 { ConnectionString = item.ConnectionString; ProviderName = item.Provider; break; } } metaInfo = DbConnectionFactory.CreateConnection(ConnectionString, ProviderName); } else { Log("DataSources 不能为空,且必须存在一个Master的数据源!", new ArgumentException("DataSources 不能为空,且必须存在一个Master的数据源!"), MessageType.Error); } } catch (Exception ex) { Log("DataSources 不能为空,且必须存在一个Master的数据源!", ex, MessageType.Error); throw new ArgumentException("DataSources 不能为空,且必须存在一个Master的数据源!", ex); } if (config.MapperSources != null) { Assembly ass = null; string _MapperSourcePath = ""; string path = ""; MapperSource.MapperAssemblyType _MapperAssemblyType = MapperSource.MapperAssemblyType.ClassType; try { databaseConfig.MappingAssemblies.Clear(); foreach (var item in config.MapperSources) { _MapperAssemblyType = item.Type; if (item.Type == MapperSource.MapperAssemblyType.File) { _MapperSourcePath = item.Path; path = FileLoader.GetPath(item.Path); ass = Assembly.LoadFrom(path); databaseConfig.MappingAssemblies.Add(ass); } else if (item.Type == MapperSource.MapperAssemblyType.ClassType) { path = item.ClassName; Type type = Type.GetType(item.ClassName); if (type != null) { ass = type.Assembly; if (ass != null) { databaseConfig.MappingAssemblies.Add(ass); } } else { Log("MapperSource 中存在不正确的Type:" + item.ClassName, new ArgumentException("MapperSource 中存在不正确的Type:" + item.ClassName), MessageType.Error); } } } foreach (var item in PureDataConfigurationLoader.MapperSourceAssemblies) { if (item != null) { databaseConfig.MappingAssemblies.Add(item); } } } catch (Exception ex) { Log("Load MapperSource error on :" + _MapperAssemblyType + ", " + _MapperSourcePath + " , path:" + path, ex, MessageType.Error); throw new ArgumentException("Load MapperSource error on :" + _MapperAssemblyType + ", " + _MapperSourcePath, ex); } } if (config.SqlMapSources != null) { var dirSqlMappers = config.SqlMapSources.Where(p => p.Type == ResourceType.Directory); var fileSqlMappers = config.SqlMapSources.Where(p => p.Type == ResourceType.File); databaseConfig.SqlMapDirPaths = dirSqlMappers.Select(p => p.Path).ToList(); databaseConfig.SqlMapFilePaths = fileSqlMappers.Select(p => p.Path).ToList(); foreach (var item in PureDataConfigurationLoader.SqlMapDirPaths) { if (item != null) { databaseConfig.SqlMapDirPaths.Add(item); } } foreach (var item in PureDataConfigurationLoader.SqlMapFilePaths) { if (item != null) { databaseConfig.SqlMapFilePaths.Add(item); } } } try { if (databaseConfig.EnableIntercept == true) { databaseConfig.Interceptors.Clear(); //if (databaseConfig.EnableDebug && databaseConfig.EnableIntercept) //{ // databaseConfig.Interceptors.Add(OutputSQLIntercept.Instance); // databaseConfig.Interceptors.Add(OutputExceptionIntercept.Instance); //} if (config.Interceptors != null) { IInterceptor ass = null; string path = ""; foreach (var item in config.Interceptors) { ass = null; if (string.IsNullOrEmpty(item.ClassFullName) || string.IsNullOrEmpty(item.AssemblyName)) { continue; } if (item.Type == InterceptorSource.InterceptorType.ConnectionInterceptor) { ass = ReflectionHelper.CreateInstance <IConnectionInterceptor>(item.ClassFullName, item.AssemblyName); } else if (item.Type == InterceptorSource.InterceptorType.ExecutingInterceptor) { ass = ReflectionHelper.CreateInstance <IExecutingInterceptor>(item.ClassFullName, item.AssemblyName); } else if (item.Type == InterceptorSource.InterceptorType.ExceptionInterceptor) { ass = ReflectionHelper.CreateInstance <IExceptionInterceptor>(item.ClassFullName, item.AssemblyName); } else if (item.Type == InterceptorSource.InterceptorType.DataInterceptor) { ass = ReflectionHelper.CreateInstance <IDataInterceptor>(item.ClassFullName, item.AssemblyName); } else if (item.Type == InterceptorSource.InterceptorType.TransactionInterceptor) { ass = ReflectionHelper.CreateInstance <ITransactionInterceptor>(item.ClassFullName, item.AssemblyName); } if (ass != null) { databaseConfig.Interceptors.Add(ass); } } } } } catch (Exception ex) { Log("Load Intercept error !", ex, MessageType.Error); throw new ArgumentException("Load Intercept error !", ex); } if (config.CodeGenTemplates != null) { databaseConfig.CodeGenTemplates = config.CodeGenTemplates; } } return(metaInfo); }