using System; using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using System.Reflection; using System.Text; namespace SqlSugar { public class ContextMethods : IContextMethods { public SqlSugarClient Context { get; set; } #region DataReader /// ///DataReader to Dynamic /// /// /// public ExpandoObject DataReaderToExpandoObject(IDataReader reader) { var result = new ExpandoObject(); var dic = ((IDictionary)result); for (int i = 0; i < reader.FieldCount; i++) { try { var addItem = reader.GetValue(i); if (addItem == DBNull.Value) addItem = null; dic.Add(reader.GetName(i), addItem); } catch { dic.Add(reader.GetName(i), null); } } return result; } /// ///DataReader to Dynamic List /// /// /// public List DataReaderToExpandoObjectList(IDataReader reader) { using (reader) { var result = new List(); if (reader != null && !reader.IsClosed) { while (reader.Read()) { result.Add(DataReaderToExpandoObject(reader)); } } return result; } } /// ///DataReader to DataReaderToDictionary /// /// /// public Dictionary DataReaderToDictionary(IDataReader reader) { var result = new Dictionary(); for (int i = 0; i < reader.FieldCount; i++) { try { var addItem = reader.GetValue(i); if (addItem == DBNull.Value) addItem = null; result.Add(reader.GetName(i), addItem); } catch { result.Add(reader.GetName(i), null); } } return result; } /// /// DataReaderToDynamicList /// /// /// /// public List DataReaderToDynamicList(IDataReader reader) { using (reader) { var tType = typeof(T); var classProperties = tType.GetProperties().ToList(); var reval = new List(); if (reader != null && !reader.IsClosed) { while (reader.Read()) { var readerValues = DataReaderToDictionary(reader); var result = new Dictionary(); foreach (var item in classProperties) { var name = item.Name; var typeName = tType.Name; if (item.PropertyType.IsClass()) { result.Add(name, DataReaderToDynamicList_Part(readerValues, item, reval)); } else { if (readerValues.Any(it => it.Key.Equals(name, StringComparison.CurrentCultureIgnoreCase))) { var addValue = readerValues.ContainsKey(name) ? readerValues[name] : readerValues[name.ToUpper()]; if (addValue == DBNull.Value) { if (item.PropertyType.IsIn(UtilConstants.IntType, UtilConstants.DecType, UtilConstants.DobType, UtilConstants.ByteType)) { addValue = 0; } else if (item.PropertyType == UtilConstants.GuidType) { addValue = Guid.Empty; } else if (item.PropertyType == UtilConstants.DateType) { addValue = DateTime.MinValue; } else { addValue = null; } } else if (item.PropertyType == UtilConstants.IntType) { addValue = Convert.ToInt32(addValue); } result.Add(name, addValue); } } } var stringValue = SerializeObject(result); reval.Add((T)DeserializeObject(stringValue)); } } return reval; } } private Dictionary DataReaderToDynamicList_Part(Dictionary readerValues, PropertyInfo item, List reval) { var result = new Dictionary(); var type = item.PropertyType; if (UtilConstants.SugarType == type) { return result; } if (type.FullName.IsCollectionsList()) { return null; } var classProperties = type.GetProperties().ToList(); foreach (var prop in classProperties) { var name = prop.Name; var typeName = type.Name; if (prop.PropertyType.IsClass()) { result.Add(name, DataReaderToDynamicList_Part(readerValues, prop, reval)); } else { var key = typeName + "." + name; if (readerValues.ContainsKey(key)) { var addItem = readerValues[key]; if (addItem == DBNull.Value) addItem = null; result.Add(name, addItem); } } } return result; } #endregion DataReader #region Serialize /// /// Serialize Object /// /// /// public string SerializeObject(object value) { DependencyManagement.TryJsonNet(); return Context.CurrentConnectionConfig.ConfigureExternalServices.SerializeService.SerializeObject(value); } /// /// Serialize Object /// /// /// public T DeserializeObject(string value) { DependencyManagement.TryJsonNet(); return Context.CurrentConnectionConfig.ConfigureExternalServices.SerializeService.DeserializeObject(value); } #endregion Serialize #region Copy Object /// /// Copy new Object /// /// /// /// public T TranslateCopy(T sourceObject) { if (sourceObject == null) return default(T); else { var jsonString = SerializeObject(sourceObject); return DeserializeObject(jsonString); } } public SqlSugarClient CopyContext(bool isCopyEvents = false) { var newClient = new SqlSugarClient(this.TranslateCopy(Context.CurrentConnectionConfig)) { MappingColumns = this.TranslateCopy(Context.MappingColumns), MappingTables = this.TranslateCopy(Context.MappingTables), IgnoreColumns = this.TranslateCopy(Context.IgnoreColumns) }; if (isCopyEvents) { newClient.Ado.IsEnableLogEvent = Context.Ado.IsEnableLogEvent; newClient.Ado.LogEventStarting = Context.Ado.LogEventStarting; newClient.Ado.LogEventCompleted = Context.Ado.LogEventCompleted; newClient.Ado.ProcessingEventStartingSQL = Context.Ado.ProcessingEventStartingSQL; } return newClient; } #endregion Copy Object #region DataTable public dynamic DataTableToDynamic(DataTable table) { var deserializeObject = new List>(); Dictionary childRow; foreach (DataRow row in table.Rows) { childRow = new Dictionary(); foreach (DataColumn col in table.Columns) { var addItem = row[col]; if (addItem == DBNull.Value) addItem = null; childRow.Add(col.ColumnName, addItem); } deserializeObject.Add(childRow); } return this.DeserializeObject(this.SerializeObject(deserializeObject)); } #endregion DataTable #region Cache public ICacheService GetReflectionInoCacheInstance() { return Context.CurrentConnectionConfig.ConfigureExternalServices.ReflectionInoCacheService; } public void RemoveCacheAll() { ReflectionInoHelper.RemoveAllCache(); } public void RemoveCacheAll() { ReflectionInoCore.GetInstance().RemoveAllCache(); } public void RemoveCache(string key) { ReflectionInoCore.GetInstance().Remove(key); } #endregion Cache #region Query public KeyValuePair ConditionalModelToSql(List models, int beginIndex = 0) { if (models.IsNullOrEmpty()) return new KeyValuePair(); var builder = new StringBuilder(); var parameters = new List(); var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig); foreach (var model in models) { if (model is ConditionalModel) { var item = model as ConditionalModel; var index = models.IndexOf(item) + beginIndex; var type = index == 0 ? "" : "AND"; if (beginIndex > 0) { type = null; } var temp = " {0} {1} {2} {3} "; var parameterName = string.Format("{0}Conditional{1}{2}", sqlBuilder.SqlParameterKeyWord, item.FieldName, index); switch (item.ConditionalType) { case ConditionalType.Equal: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "=", parameterName); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.Like: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName); parameters.Add(new SugarParameter(parameterName, "%" + item.FieldValue + "%")); break; case ConditionalType.GreaterThan: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">", parameterName); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.GreaterThanOrEqual: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">=", parameterName); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.LessThan: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<", parameterName); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.LessThanOrEqual: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<=", parameterName); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.In: if (item.FieldValue == null) item.FieldValue = string.Empty; var inValue1 = ("(" + item.FieldValue.Split(',').ToJoinSqlInVals() + ")"); builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "IN", inValue1); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.NotIn: if (item.FieldValue == null) item.FieldValue = string.Empty; var inValue2 = ("(" + item.FieldValue.Split(',').ToJoinSqlInVals() + ")"); builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "NOT IN", inValue2); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.LikeLeft: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName); parameters.Add(new SugarParameter(parameterName, item.FieldValue + "%")); break; case ConditionalType.LikeRight: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "LIKE", parameterName); parameters.Add(new SugarParameter(parameterName, "%" + item.FieldValue)); break; case ConditionalType.NoEqual: builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<>", parameterName); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.IsNullOrEmpty: builder.AppendFormat("{0} ({1}) OR ({2}) ", type, item.FieldName.ToSqlFilter() + " IS NULL ", item.FieldName.ToSqlFilter() + " = '' "); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.IsNot: if (item.FieldValue == null) { builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), " IS NOT ", "NULL"); } else { builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<>", parameterName); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); } break; case ConditionalType.CharIndexLeft: builder.AppendFormat(temp, type, "CHARINDEX(" + item.FieldName.ToSqlFilter(), ",", parameterName + ")>0"); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; case ConditionalType.CharIndexRight: builder.AppendFormat(temp, type, "CHARINDEX(" + parameterName, ",", item.FieldName.ToSqlFilter() + ")>0"); parameters.Add(new SugarParameter(parameterName, item.FieldValue)); break; default: break; } } else { var item = model as ConditionalCollections; if (item != null) { foreach (var con in item.ConditionalList) { var index = item.ConditionalList.IndexOf(con); var isFirst = index == 0; var isLast = index == (item.ConditionalList.Count - 1); if (isFirst) { builder.AppendFormat(" {0} ( ", con.Key.ToString().ToUpper()); } var conModels = new List(); conModels.Add(con.Value); var childSqlInfo = ConditionalModelToSql(conModels, 1000 * (1 + index)); if (!isFirst) { builder.AppendFormat(" {0} ", con.Key.ToString().ToUpper()); } builder.Append(childSqlInfo.Key); parameters.AddRange(childSqlInfo.Value); if (isLast) { builder.Append(" ) "); } else { } } } } } return new KeyValuePair(builder.ToString(), parameters.ToArray()); } #endregion Query } }