Пример #1
0
 private void SetUpdateItemByEntity(int i, T item, List <DbColumnInfo> updateItem)
 {
     foreach (var column in EntityInfo.Columns)
     {
         if (column.IsIgnore)
         {
             continue;
         }
         var columnInfo = new DbColumnInfo()
         {
             Value        = column.PropertyInfo.GetValue(item, null),
             DbColumnName = GetDbColumnName(column.PropertyName),
             PropertyName = column.PropertyName,
             PropertyType = UtilMethods.GetUnderType(column.PropertyInfo),
             TableId      = i
         };
         if (columnInfo.PropertyType.IsEnum() && columnInfo.Value != null)
         {
             columnInfo.Value = Convert.ToInt64(columnInfo.Value);
         }
         if (column.IsJson)
         {
             columnInfo.IsJson = true;
             if (columnInfo.Value != null)
             {
                 columnInfo.Value = this.Context.Utilities.SerializeObject(columnInfo.Value);
             }
         }
         if (column.IsArray)
         {
             columnInfo.IsArray = true;
         }
         var tranColumn = EntityInfo.Columns.FirstOrDefault(it => it.IsTranscoding && it.DbColumnName.Equals(column.DbColumnName, StringComparison.CurrentCultureIgnoreCase));
         if (tranColumn != null && columnInfo.Value.HasValue())
         {
             columnInfo.Value = UtilMethods.EncodeBase64(columnInfo.Value.ToString());
         }
         updateItem.Add(columnInfo);
     }
     this.UpdateBuilder.DbColumnInfoList.AddRange(updateItem);
 }
Пример #2
0
 public override object FormatValue(object value)
 {
     if (value == null)
     {
         return "NULL";
     }
     else
     {
         var type = UtilMethods.GetUnderType(value.GetType());
         if (type == UtilConstants.DateType)
         {
             var date = value.ObjToDate();
             if (date < Convert.ToDateTime("1900-1-1"))
             {
                 date = Convert.ToDateTime("1900-1-1");
             }
             return "to_date('"+ date.ToString("yyyy-MM-dd HH:mm:ss") + "', 'YYYY-MM-DD HH24:MI:SS') ";  
         }
         else if (type.IsEnum())
         {
             return Convert.ToInt64(value);
         }
         else if (type == UtilConstants.ByteArrayType)
         {
             string bytesString = "0x" + BitConverter.ToString((byte[])value).Replace("-", "");
             return bytesString;
         }
         else if (type == UtilConstants.BoolType)
         {
             return value.ObjToBool() ? "1" : "0";
         }
         else if (type == UtilConstants.StringType || type == UtilConstants.ObjType)
         {
             return "N'" + value.ToString().ToSqlFilter() + "'";
         }
         else
         {
             return "N'" + value.ToString() + "'";
         }
     }
 }
Пример #3
0
 public virtual object FormatValue(object value)
 {
     if (value == null)
     {
         return("NULL");
     }
     else
     {
         var type = UtilMethods.GetUnderType(value.GetType());
         if (type == UtilConstants.DateType)
         {
             var date = value.ObjToDate();
             if (date < Convert.ToDateTime("1900-1-1"))
             {
                 date = Convert.ToDateTime("1900-1-1");
             }
             return("'" + date.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'");
         }
         else if (type == UtilConstants.ByteArrayType)
         {
             string bytesString = "0x" + BitConverter.ToString((byte[])value).Replace("-", "");
             return(bytesString);
         }
         else if (type.IsEnum())
         {
             return(Convert.ToInt64(value));
         }
         else if (type == UtilConstants.BoolType)
         {
             return(value.ObjToBool() ? "1" : "0");
         }
         else if (type == UtilConstants.StringType || type == UtilConstants.ObjType)
         {
             return("N'" + value.ToString().ToSqlFilter() + "'");
         }
         else
         {
             return("N'" + value.ToString() + "'");
         }
     }
 }
Пример #4
0
        private void Init()
        {
            if (datas.Count == 1)
            {
                isDates = true;
                var data = datas.First();
                if (data is ReportableDateType)
                {
                    var type = UtilMethods.ChangeType2(data, typeof(ReportableDateType));
                    switch (type)
                    {
                    case ReportableDateType.MonthsInLast1years:
                        dates.AddRange(GetMonths(1));
                        break;

                    case ReportableDateType.MonthsInLast3years:
                        dates.AddRange(GetMonths(3));
                        break;

                    case ReportableDateType.MonthsInLast10years:
                        dates.AddRange(GetMonths(10));
                        break;

                    case ReportableDateType.years1:
                        dates.AddRange(GetYears(1));
                        break;

                    case ReportableDateType.years3:
                        dates.AddRange(GetYears(3));
                        break;

                    case ReportableDateType.years10:
                        dates.AddRange(GetYears(10));
                        break;

                    default:
                        break;
                    }
                }
            }
        }
Пример #5
0
        private static void GetValueTypeList <T>(Type type, IDataReader dataReader, List <T> result)
        {
            var value = dataReader.GetValue(0);

            if (type == UtilConstants.GuidType)
            {
                value = Guid.Parse(value.ToString());
            }
            if (value == DBNull.Value)
            {
                result.Add(default(T));
            }
            else if (type.IsEnum)
            {
                result.Add((T)Enum.Parse(type, value.ObjToString()));
            }
            else
            {
                result.Add((T)Convert.ChangeType(value, UtilMethods.GetUnderType(type)));
            }
        }
Пример #6
0
        protected virtual bool IsSamgeType(EntityColumnInfo ec, DbColumnInfo dc)
        {
            if (!string.IsNullOrEmpty(ec.DataType))
            {
                return(ec.DataType != dc.DataType);
            }
            var propertyType    = UtilMethods.GetUnderType(ec.PropertyInfo);
            var properyTypeName = string.Empty;

            if (propertyType.IsEnum())
            {
                properyTypeName = this.Context.Ado.DbBind.GetDbTypeName(ec.Length > 9 ? UtilConstants.LongType.Name : UtilConstants.IntType.Name);
            }
            else
            {
                properyTypeName = this.Context.Ado.DbBind.GetDbTypeName(propertyType.Name);
            }
            var dataType = dc.DataType;

            return(properyTypeName != dataType);
        }
Пример #7
0
        protected List <T> GetValueTypeList <T>(Type type, IDataReader dataReader)
        {
            List <T> reval = new List <T>();

            using (IDataReader re = dataReader)
            {
                while (re.Read())
                {
                    var value = re.GetValue(0);
                    if (value == DBNull.Value)
                    {
                        reval.Add(default(T));
                    }
                    else
                    {
                        reval.Add((T)Convert.ChangeType(re.GetValue(0), UtilMethods.GetUnderType(type)));
                    }
                }
            }
            return(reval);
        }
Пример #8
0
 private static void AddIdentificationList(QueryBuilder queryBuilder, CacheKey result)
 {
     result.IdentificationList = new List <string>();
     result.IdentificationList.Add(queryBuilder.GetTableNameString);
     result.IdentificationList.Add(queryBuilder.GetJoinValueString);
     result.IdentificationList.Add(queryBuilder.GetOrderByString);
     result.IdentificationList.Add(queryBuilder.GetGroupByString);
     result.IdentificationList.Add(queryBuilder.GetWhereValueString);
     result.IdentificationList.Add(queryBuilder.PartitionByValue);
     result.IdentificationList.Add(queryBuilder.Take.ObjToString());
     result.IdentificationList.Add(queryBuilder.Skip.ObjToString());
     result.IdentificationList.Add(queryBuilder.IsCount.ObjToString());
     result.IdentificationList.Add(UtilMethods.GetMD5(queryBuilder.GetSelectValue.ObjToString()));
     if (queryBuilder.Parameters.HasValue())
     {
         foreach (var item in queryBuilder.Parameters)
         {
             result.IdentificationList.Add(item.ParameterName + "_" + item.Value);
         }
     }
 }
Пример #9
0
        protected List <T> GetValueTypeList <T>(Type type, IDataReader dataReader)
        {
            List <T> reval = new List <T>();

            while (dataReader.Read())
            {
                var value = dataReader.GetValue(0);
                if (type == UtilConstants.GuidType)
                {
                    value = Guid.Parse(value.ToString());
                }
                if (value == DBNull.Value)
                {
                    reval.Add(default(T));
                }
                else
                {
                    reval.Add((T)Convert.ChangeType(value, UtilMethods.GetUnderType(type)));
                }
            }
            return(reval);
        }
        public string GetValue(object entityValue)
        {
            if (entityValue == null)
            {
                return(null);
            }
            var type = UtilMethods.GetUnderType(entityValue.GetType());

            if (UtilConstants.NumericalTypes.Contains(type))
            {
                return(entityValue.ToString());
            }
            else if (type == UtilConstants.DateType)
            {
                return(this.DbMehtods.ToDate(new MethodCallExpressionModel()
                {
                    Args = new System.Collections.Generic.List <MethodCallExpressionArgs>()
                    {
                        new MethodCallExpressionArgs()
                        {
                            MemberName = $"'{entityValue}'"
                        }
                    }
                }));
            }
            else
            {
                return(this.DbMehtods.ToString(new MethodCallExpressionModel()
                {
                    Args = new System.Collections.Generic.List <MethodCallExpressionArgs>()
                    {
                        new MethodCallExpressionArgs()
                        {
                            MemberName = $"'{entityValue}'"
                        }
                    }
                }));
            }
        }
Пример #11
0
        protected override DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item)
        {
            var result = new DbColumnInfo()
            {
                DataType          = this.Context.Ado.DbBind.GetDbTypeName(UtilMethods.GetUnderType(item.PropertyInfo).Name),
                TableId           = entityInfo.Columns.IndexOf(item),
                DbColumnName      = item.DbColumnName.IsValuable() ? item.DbColumnName : item.PropertyName,
                IsPrimarykey      = item.IsPrimarykey,
                IsIdentity        = item.IsIdentity,
                TableName         = tableName,
                IsNullable        = item.IsNullable,
                DefaultValue      = item.DefaultValue,
                ColumnDescription = item.ColumnDescription,
                Length            = item.Length
            };

            if (result.DataType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase) && result.Length == 0)
            {
                result.Length = 1;
            }
            return(result);
        }
 private void Select(MemberInitExpression expression, ExpressionParameter parameter, bool isSingle)
 {
     foreach (MemberBinding binding in expression.Bindings)
     {
         if (binding.BindingType != MemberBindingType.Assignment)
         {
             throw new NotSupportedException();
         }
         MemberAssignment memberAssignment = (MemberAssignment)binding;
         var memberName = memberAssignment.Member.Name;
         var item       = memberAssignment.Expression;
         if (IsNullable(item) && item is UnaryExpression)
         {
             var memtype = ExpressionTool.GetMemberInfoType(memberAssignment.Member);
             if (IsNullable(memtype) && UtilMethods.GetUnderType(memtype) == UtilMethods.GetUnderType(item.Type))
             {
                 item = (item as UnaryExpression).Operand;
             }
         }
         ResolveNewExpressions(parameter, item, memberName);
     }
 }
Пример #13
0
 private void SetConditList(List <StorageableInfo <T> > itemList, List <EntityColumnInfo> whereColumns, List <IConditionalModel> conditList)
 {
     ;
     foreach (var dataItem in itemList)
     {
         var condition = new ConditionalCollections()
         {
             ConditionalList = new List <KeyValuePair <WhereType, SqlSugar.ConditionalModel> >()
         };
         conditList.Add(condition);
         int i = 0;
         foreach (var item in whereColumns)
         {
             var value = item.PropertyInfo.GetValue(dataItem.Item, null);
             if (value != null && value.GetType().IsEnum())
             {
                 if (this.Context.CurrentConnectionConfig.MoreSettings?.TableEnumIsString == true)
                 {
                     value = value.ToString();
                 }
                 else
                 {
                     value = Convert.ToInt64(value);
                 }
             }
             condition.ConditionalList.Add(new KeyValuePair <WhereType, ConditionalModel>(i == 0?WhereType.Or :WhereType.And, new ConditionalModel()
             {
                 FieldName             = item.DbColumnName,
                 ConditionalType       = ConditionalType.Equal,
                 CSharpTypeName        = UtilMethods.GetTypeName(value),
                 FieldValue            = value + "",
                 FieldValueConvertFunc = this.Context.CurrentConnectionConfig.DbType == DbType.PostgreSQL?
                                         UtilMethods.GetTypeConvert(value):null
             }));
             ++i;
         }
     }
 }
Пример #14
0
 private void SetInsertItemByEntity(int i, T item, List <DbColumnInfo> insertItem)
 {
     foreach (var column in EntityInfo.Columns)
     {
         if (column.IsIgnore || column.IsOnlyIgnoreInsert)
         {
             continue;
         }
         var columnInfo = new DbColumnInfo()
         {
             Value        = column.PropertyInfo.GetValue(item, null),
             DbColumnName = GetDbColumnName(column.PropertyName),
             PropertyName = column.PropertyName,
             PropertyType = UtilMethods.GetUnderType(column.PropertyInfo),
             TableId      = i
         };
         if (columnInfo.PropertyType.IsEnum())
         {
             columnInfo.Value = Convert.ToInt64(columnInfo.Value);
         }
         insertItem.Add(columnInfo);
     }
 }
Пример #15
0
        internal void Init()
        {
            this.UpdateBuilder.TableName = EntityInfo.EntityName;
            if (IsMappingTable)
            {
                var mappingInfo = this.Context.MappingTables.SingleOrDefault(it => it.EntityName == EntityInfo.EntityName);
                if (mappingInfo != null)
                {
                    this.UpdateBuilder.TableName = mappingInfo.DbTableName;
                }
            }
            Check.Exception(UpdateObjs == null || UpdateObjs.Count() == 0, "UpdateObjs is null");
            int i = 0;

            foreach (var item in UpdateObjs)
            {
                List <DbColumnInfo> updateItem = new List <DbColumnInfo>();
                foreach (var column in EntityInfo.Columns)
                {
                    var columnInfo = new DbColumnInfo()
                    {
                        Value        = column.PropertyInfo.GetValue(item, null),
                        DbColumnName = GetDbColumnName(column.PropertyName),
                        PropertyName = column.PropertyName,
                        PropertyType = UtilMethods.GetUnderType(column.PropertyInfo),
                        TableId      = i
                    };
                    if (columnInfo.PropertyType.IsEnum())
                    {
                        columnInfo.Value = Convert.ToInt64(columnInfo.Value);
                    }
                    updateItem.Add(columnInfo);
                }
                this.UpdateBuilder.DbColumnInfoList.AddRange(updateItem);
                ++i;
            }
        }
Пример #16
0
 private void MethodCall(ExpressionParameter parameter, string memberName, Expression item)
 {
     if (IsSubMethod(item as MethodCallExpression))
     {
         UtilMethods.GetOldValue(parameter.CommonTempData, () =>
         {
             parameter.CommonTempData = CommonTempDataType.Result;
             base.Expression          = item;
             base.Start();
             var subSql = base.Context.GetEqString(memberName, parameter.CommonTempData.ObjToString());
             if (ResolveExpressType.Update == this.Context.ResolveType)
             {
                 subSql = Regex.Replace(subSql, @" \[\w+?\]\.", this.Context.GetTranslationTableName(parameter.CurrentExpression.Type.Name, true) + ".");
             }
             parameter.Context.Result.Append(subSql);
         });
     }
     else
     {
         base.Expression = item;
         base.Start();
         parameter.Context.Result.Append(base.Context.GetEqString(memberName, parameter.CommonTempData.ObjToString()));
     }
 }
Пример #17
0
 private void SetUpdateItemByEntity(int i, T item, List <DbColumnInfo> updateItem)
 {
     foreach (var column in EntityInfo.Columns)
     {
         if (column.IsIgnore)
         {
             continue;
         }
         var columnInfo = new DbColumnInfo()
         {
             Value        = column.PropertyInfo.GetValue(item, null),
             DbColumnName = GetDbColumnName(column.PropertyName),
             PropertyName = column.PropertyName,
             PropertyType = UtilMethods.GetUnderType(column.PropertyInfo),
             TableId      = i
         };
         if (columnInfo.PropertyType.IsEnum())
         {
             columnInfo.Value = Convert.ToInt64(columnInfo.Value);
         }
         updateItem.Add(columnInfo);
     }
     this.UpdateBuilder.DbColumnInfoList.AddRange(updateItem);
 }
Пример #18
0
        private void ResolveHasValue(ExpressionParameter parameter, MemberExpression expression)
        {
            parameter.CommonTempData = CommonTempDataType.Result;
            this.Expression          = expression.Expression;
            this.Start();
            var methodParamter = new MethodCallExpressionArgs()
            {
                IsMember = true, MemberName = parameter.CommonTempData, MemberValue = null
            };

            if (expression.Expression?.Type != null)
            {
                methodParamter.Type = UtilMethods.GetUnderType(expression.Expression?.Type);
            }
            var result = this.Context.DbMehtods.HasValue(new MethodCallExpressionModel()
            {
                Args = new List <MethodCallExpressionArgs>()
                {
                    methodParamter
                }
            });

            if (parameter.BaseExpression != null && ExpressionTool.IsLogicOperator(parameter.BaseExpression) && parameter.IsLeft == true)
            {
                if (base.Context.Result.Contains(ExpressionConst.FormatSymbol))
                {
                    base.Context.Result.Replace(ExpressionConst.FormatSymbol, "");
                }
                this.Context.Result.Append(result + " " + ExpressionTool.GetOperator(parameter.BaseExpression.NodeType) + " ");
            }
            else
            {
                this.Context.Result.Append(result);
            }
            parameter.CommonTempData = null;
        }
Пример #19
0
        public override void NoExistLogic(EntityInfo entityInfo)
        {
            var tableName = GetTableName(entityInfo);
            //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1");
            List <DbColumnInfo> columns = new List <DbColumnInfo>();

            if (entityInfo.Columns.HasValue())
            {
                foreach (var item in entityInfo.Columns.OrderBy(it => it.IsPrimarykey ? 0 : 1))
                {
                    if (item.IsIgnore)
                    {
                        continue;
                    }
                    if (item.PropertyInfo != null && UtilMethods.GetUnderType(item.PropertyInfo.PropertyType) == UtilConstants.GuidType && item.Length == 0 && item.DataType == null)
                    {
                        item.Length = Guid.NewGuid().ToString().Length;
                    }
                    DbColumnInfo dbColumnInfo = this.EntityColumnToDbColumn(entityInfo, tableName, item);
                    columns.Add(dbColumnInfo);
                }
            }
            this.Context.DbMaintenance.CreateTable(tableName, columns, true);
        }
Пример #20
0
 public virtual string GetPackTable(string sql, string shortName)
 {
     return(UtilMethods.GetPackTable(sql, shortName));
 }
        private void BindMethod(ILGenerator generator, EntityColumnInfo columnInfo, int ordinal)
        {
            IDbBind    bind             = Context.Ado.DbBind;
            bool       isNullableType   = false;
            MethodInfo method           = null;
            Type       bindPropertyType = UtilMethods.GetUnderType(columnInfo.PropertyInfo, ref isNullableType);
            string     dbTypeName       = UtilMethods.GetParenthesesValue(DataRecord.GetDataTypeName(ordinal));

            if (dbTypeName.IsNullOrEmpty())
            {
                dbTypeName = bindPropertyType.Name;
            }
            string propertyName      = columnInfo.PropertyName;
            string validPropertyName = bind.GetPropertyTypeName(dbTypeName);

            validPropertyName = validPropertyName == "byte[]" ? "byteArray" : validPropertyName;
            CSharpDataType validPropertyType = (CSharpDataType)Enum.Parse(typeof(CSharpDataType), validPropertyName);

            #region Sqlite Logic
            if (this.Context.CurrentConnectionConfig.DbType == DbType.Sqlite)
            {
                if (bindPropertyType.IsEnum())
                {
                    method = isNullableType ? getConvertEnum_Null.MakeGenericMethod(bindPropertyType) : getEnum.MakeGenericMethod(bindPropertyType);
                }
                else if (bindPropertyType == UtilConstants.IntType)
                {
                    method = isNullableType ? getConvertInt32 : getInt32;
                }
                else if (bindPropertyType == UtilConstants.ByteType)
                {
                    method = isNullableType ? getConvertByte : getByte;
                }
                else if (bindPropertyType == UtilConstants.StringType && dbTypeName?.ToLower() == "timestamp")
                {
                    method = isNullableType ? getOtherNull.MakeGenericMethod(bindPropertyType) : getOther.MakeGenericMethod(bindPropertyType);
                }
                else if (bindPropertyType == UtilConstants.StringType)
                {
                    method = getString;
                }
                else
                {
                    method = isNullableType ? getOtherNull.MakeGenericMethod(bindPropertyType) : getOther.MakeGenericMethod(bindPropertyType);
                }

                if (method.IsVirtual)
                {
                    generator.Emit(OpCodes.Callvirt, method);
                }
                else
                {
                    generator.Emit(OpCodes.Call, method);
                }
                return;
            }
            ;
            #endregion

            #region Common Database Logic
            string bindProperyTypeName = bindPropertyType.Name.ToLower();
            bool   isEnum = bindPropertyType.IsEnum();
            if (isEnum)
            {
                validPropertyType = CSharpDataType.@enum;
            }
            switch (validPropertyType)
            {
            case CSharpDataType.@int:
                CheckType(bind.IntThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName.IsContainsIn("int", "int32"))
                {
                    method = isNullableType ? getConvertInt32 : getInt32;
                }
                if (bindProperyTypeName.IsContainsIn("int64"))
                {
                    method = isNullableType ? getConvertInt64 : getInt64;
                }
                if (bindProperyTypeName.IsContainsIn("byte"))
                {
                    method = isNullableType ? getConvertByte : getByte;
                }
                if (bindProperyTypeName.IsContainsIn("int16"))
                {
                    method = isNullableType ? getConvertInt16 : getInt16;
                }
                break;

            case CSharpDataType.@bool:
                if (bindProperyTypeName == "bool" || bindProperyTypeName == "boolean")
                {
                    method = isNullableType ? getConvertBoolean : getBoolean;
                }
                break;

            case CSharpDataType.@string:
                if (this.Context.CurrentConnectionConfig.DbType != DbType.Oracle)
                {
                    CheckType(bind.StringThrow, bindProperyTypeName, validPropertyName, propertyName);
                }
                method = getString;
                if (bindProperyTypeName == "guid")
                {
                    method = isNullableType ? getConvertStringGuid : getStringGuid;
                }
                break;

            case CSharpDataType.DateTime:
                CheckType(bind.DateThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "datetime")
                {
                    method = isNullableType ? getConvertDateTime : getDateTime;
                }
                if (bindProperyTypeName == "datetime" && dbTypeName.ToLower() == "time")
                {
                    method = isNullableType ? getConvertTime : getTime;
                }
                if (bindProperyTypeName == "datetimeoffset")
                {
                    method = isNullableType ? getConvertdatetimeoffset : getdatetimeoffset;
                }
                break;

            case CSharpDataType.@decimal:
                CheckType(bind.DecimalThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "decimal")
                {
                    method = isNullableType ? getConvertDecimal : getDecimal;
                }
                break;

            case CSharpDataType.@float:
            case CSharpDataType.@double:
                CheckType(bind.DoubleThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName.IsIn("double", "single") && dbTypeName != "real")
                {
                    method = isNullableType ? getConvertDouble : getDouble;
                }
                else
                {
                    method = isNullableType ? getConvertFloat : getFloat;
                }
                if (dbTypeName.Equals("float", StringComparison.CurrentCultureIgnoreCase) && isNullableType && bindProperyTypeName.Equals("single", StringComparison.CurrentCultureIgnoreCase))
                {
                    method = getConvertDoubleToFloat;
                }
                if (bindPropertyType == UtilConstants.DecType)
                {
                    method = isNullableType ? getOtherNull.MakeGenericMethod(bindPropertyType) : getOther.MakeGenericMethod(bindPropertyType);
                }
                if (bindPropertyType == UtilConstants.IntType)
                {
                    method = isNullableType ? getOtherNull.MakeGenericMethod(bindPropertyType) : getOther.MakeGenericMethod(bindPropertyType);
                }
                break;

            case CSharpDataType.Guid:
                CheckType(bind.GuidThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "guid")
                {
                    method = isNullableType ? getConvertGuid : getGuid;
                }
                break;

            case CSharpDataType.@byte:
                if (bindProperyTypeName == "byte")
                {
                    method = isNullableType ? getConvertByte : getByte;
                }
                break;

            case CSharpDataType.@enum:
                method = isNullableType ? getConvertEnum_Null.MakeGenericMethod(bindPropertyType) : getEnum.MakeGenericMethod(bindPropertyType);
                break;

            case CSharpDataType.@short:
                CheckType(bind.ShortThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "int16" || bindProperyTypeName == "short")
                {
                    method = isNullableType ? getConvertInt16 : getInt16;
                }
                break;

            case CSharpDataType.@long:
                if (bindProperyTypeName == "int64" || bindProperyTypeName == "long")
                {
                    method = isNullableType ? getConvertInt64 : getInt64;
                }
                break;

            case CSharpDataType.DateTimeOffset:
                method = isNullableType ? getConvertdatetimeoffset : getdatetimeoffset;
                if (bindProperyTypeName == "datetime")
                {
                    method = isNullableType ? getConvertdatetimeoffsetDate : getdatetimeoffsetDate;
                }
                break;

            case CSharpDataType.Single:
                break;

            default:
                method = isNullableType ? getOtherNull.MakeGenericMethod(bindPropertyType) : getOther.MakeGenericMethod(bindPropertyType);
                break;
            }
            if (method == null && bindPropertyType == UtilConstants.StringType)
            {
                method = getConvertString;
            }
            if (bindPropertyType == UtilConstants.ObjType)
            {
                method = isNullableType ? getOtherNull.MakeGenericMethod(bindPropertyType) : getOther.MakeGenericMethod(bindPropertyType);
            }
            if (method == null)
            {
                method = isNullableType ? getOtherNull.MakeGenericMethod(bindPropertyType) : getOther.MakeGenericMethod(bindPropertyType);
            }

            if (method.IsVirtual)
            {
                generator.Emit(OpCodes.Callvirt, method);
            }
            else
            {
                generator.Emit(OpCodes.Call, method);
            }
            #endregion
        }
Пример #22
0
        public virtual void ExistLogic(EntityInfo entityInfo)
        {
            if (entityInfo.Columns.HasValue())
            {
                Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1");

                var tableName = GetTableName(entityInfo);
                var dbColumns = this.Context.DbMaintenance.GetColumnInfosByTableName(tableName);
                ConvertColumns(dbColumns);
                var entityColumns = entityInfo.Columns.Where(it => it.IsIgnore == false).ToList();
                var dropColumns   = dbColumns
                                    .Where(dc => !entityColumns.Any(ec => dc.DbColumnName.Equals(ec.OldDbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                    .Where(dc => !entityColumns.Any(ec => dc.DbColumnName.Equals(ec.DbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                    .ToList();
                var addColumns = entityColumns
                                 .Where(ec => ec.OldDbColumnName.IsNullOrEmpty() || !dbColumns.Any(dc => dc.DbColumnName.Equals(ec.OldDbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                 .Where(ec => !dbColumns.Any(dc => ec.DbColumnName.Equals(dc.DbColumnName, StringComparison.CurrentCultureIgnoreCase))).ToList();
                var alterColumns = entityColumns
                                   .Where(ec => !dbColumns.Any(dc => dc.DbColumnName.Equals(ec.OldDbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                   .Where(ec =>
                                          dbColumns.Any(dc => dc.DbColumnName.Equals(ec.DbColumnName) &&
                                                        ((ec.Length != dc.Length && !UtilMethods.GetUnderType(ec.PropertyInfo).IsEnum() && UtilMethods.GetUnderType(ec.PropertyInfo).IsIn(UtilConstants.StringType)) ||
                                                         ec.IsNullable != dc.IsNullable ||
                                                         IsSamgeType(ec, dc)))).ToList();
                var renameColumns = entityColumns
                                    .Where(it => !string.IsNullOrEmpty(it.OldDbColumnName))
                                    .Where(entityColumn => dbColumns.Any(dbColumn => entityColumn.OldDbColumnName.Equals(dbColumn.DbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                    .ToList();


                var isChange = false;
                foreach (var item in addColumns)
                {
                    this.Context.DbMaintenance.AddColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item));
                    isChange = true;
                }
                foreach (var item in dropColumns)
                {
                    this.Context.DbMaintenance.DropColumn(tableName, item.DbColumnName);
                    isChange = true;
                }
                foreach (var item in alterColumns)
                {
                    this.Context.DbMaintenance.UpdateColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item));
                    isChange = true;
                }
                foreach (var item in renameColumns)
                {
                    this.Context.DbMaintenance.RenameColumn(tableName, item.OldDbColumnName, item.DbColumnName);
                    isChange = true;
                }

                foreach (var item in entityColumns)
                {
                    var dbColumn = dbColumns.FirstOrDefault(dc => dc.DbColumnName.Equals(item.DbColumnName, StringComparison.CurrentCultureIgnoreCase));
                    if (dbColumn == null)
                    {
                        continue;
                    }
                    var pkDiff       = item.IsPrimarykey != dbColumn.IsPrimarykey;
                    var idEntityDiff = item.IsIdentity != dbColumn.IsIdentity;
                    if (dbColumn != null && pkDiff && !idEntityDiff)
                    {
                        var isAdd = item.IsPrimarykey;
                        if (isAdd)
                        {
                            this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName);
                        }
                        else
                        {
                            this.Context.DbMaintenance.DropConstraint(tableName, string.Format("PK_{0}_{1}", tableName, item.DbColumnName));
                        }
                    }
                    else if (pkDiff || idEntityDiff)
                    {
                        ChangeKey(entityInfo, tableName, item);
                    }
                }
                if (isChange && IsBackupTable)
                {
                    this.Context.DbMaintenance.BackupTable(tableName, tableName + DateTime.Now.ToString("yyyyMMddHHmmss"), MaxBackupDataRows);
                }
            }
        }
        private void BindMethod(ILGenerator generator, PropertyInfo bindProperty, int ordinal)
        {
            IDbBind    bind             = Context.Ado.DbBind;
            bool       isNullableType   = false;
            MethodInfo method           = null;
            Type       bindPropertyType = UtilMethods.GetUnderType(bindProperty, ref isNullableType);
            string     dbTypeName       = DataRecord.GetDataTypeName(ordinal);

            if (Regex.IsMatch(dbTypeName, @"\(.+\)"))
            {
                dbTypeName = Regex.Replace(dbTypeName, @"\(.+\)", "");
            }
            string propertyName      = bindProperty.Name;
            string validPropertyName = bind.GetPropertyTypeName(dbTypeName);

            validPropertyName = validPropertyName == "byte[]" ? "byteArray" : validPropertyName;
            CSharpDataType validPropertyType = (CSharpDataType)Enum.Parse(typeof(CSharpDataType), validPropertyName);

            #region Sqlite Logic
            if (this.Context.CurrentConnectionConfig.DbType == DbType.Sqlite)
            {
                if (bindPropertyType.IsEnum())
                {
                    method = isNullableType ? getConvertEnum_Null.MakeGenericMethod(bindPropertyType) : getEnum.MakeGenericMethod(bindPropertyType);
                }
                else if (bindPropertyType == UtilConstants.IntType)
                {
                    method = isNullableType ? getConvertInt32 : getInt32;
                }
                else if (bindPropertyType == UtilConstants.StringType)
                {
                    method = getString;
                }
                else if (bindPropertyType == UtilConstants.ByteArrayType)
                {
                    method = getValueMethod;
                    generator.Emit(OpCodes.Call, method);
                    generator.Emit(OpCodes.Unbox_Any, bindProperty.PropertyType);
                    return;
                }
                else
                {
                    method = isNullableType ? getSqliteTypeNull.MakeGenericMethod(bindPropertyType) : getSqliteType.MakeGenericMethod(bindPropertyType);
                }
                generator.Emit(OpCodes.Call, method);
                return;
            }
            ;
            #endregion

            #region Common Database Logic
            string bindProperyTypeName = bindPropertyType.Name.ToLower();
            bool   isEnum = bindPropertyType.IsEnum();
            if (isEnum)
            {
                validPropertyType = CSharpDataType.@enum;
            }
            switch (validPropertyType)
            {
            case CSharpDataType.@int:
                CheckType(bind.IntThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName.IsContainsIn("int", "int32"))
                {
                    method = isNullableType ? getConvertInt32 : getInt32;
                }
                if (bindProperyTypeName.IsContainsIn("int64"))
                {
                    method = isNullableType ? getConvertInt64 : getInt64;
                }
                if (bindProperyTypeName.IsContainsIn("byte"))
                {
                    method = isNullableType ? getConvertByte : getByte;
                }
                if (bindProperyTypeName.IsContainsIn("int16"))
                {
                    method = isNullableType ? getConvertInt16 : getInt16;
                }
                break;

            case CSharpDataType.@bool:
                if (bindProperyTypeName == "bool" || bindProperyTypeName == "boolean")
                {
                    method = isNullableType ? getConvertBoolean : getBoolean;
                }
                break;

            case CSharpDataType.@string:
                CheckType(bind.StringThrow, bindProperyTypeName, validPropertyName, propertyName);
                method = getString;
                if (bindProperyTypeName == "guid")
                {
                    method = isNullableType? getConvertStringGuid : getStringGuid;
                }
                break;

            case CSharpDataType.DateTime:
                CheckType(bind.DateThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "datetime")
                {
                    method = isNullableType ? getConvertDateTime : getDateTime;
                }
                break;

            case CSharpDataType.@decimal:
                CheckType(bind.DecimalThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "decimal")
                {
                    method = isNullableType ? getConvertDecimal : getDecimal;
                }
                break;

            case CSharpDataType.@float:
            case CSharpDataType.@double:
                CheckType(bind.DoubleThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "double")
                {
                    method = isNullableType ? getConvertDouble : getDouble;
                }
                if (bindProperyTypeName == "single")
                {
                    method = isNullableType ? getConvertFloat : getFloat;
                }
                break;

            case CSharpDataType.Guid:
                CheckType(bind.GuidThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "guid")
                {
                    method = isNullableType ? getConvertGuid : getGuid;
                }
                break;

            case CSharpDataType.@byte:
                if (bindProperyTypeName == "byte")
                {
                    method = isNullableType ? getConvertByte : getByte;
                }
                break;

            case CSharpDataType.@enum:
                method = isNullableType ? getConvertEnum_Null.MakeGenericMethod(bindPropertyType) : getEnum.MakeGenericMethod(bindPropertyType);
                break;

            case CSharpDataType.@short:
                CheckType(bind.ShortThrow, bindProperyTypeName, validPropertyName, propertyName);
                if (bindProperyTypeName == "int16" || bindProperyTypeName == "short")
                {
                    method = isNullableType ? getConvertInt16 : getInt16;
                }
                break;

            case CSharpDataType.@long:
                if (bindProperyTypeName == "int64" || bindProperyTypeName == "long")
                {
                    method = isNullableType ? getConvertInt64 : getInt64;
                }
                break;

            case CSharpDataType.DateTimeOffset:
                method = isNullableType ? getConvertdatetimeoffset : getdatetimeoffset;
                if (bindProperyTypeName == "datetime")
                {
                    method = isNullableType ? getConvertdatetimeoffsetDate : getdatetimeoffsetDate;
                }
                break;

            default:
                method = getValueMethod;
                break;
            }
            if (method == null && bindPropertyType == UtilConstants.StringType)
            {
                method = getConvertString;
            }
            if (method == null)
            {
                method = isNullableType ? getOtherNull.MakeGenericMethod(bindPropertyType) : getOther.MakeGenericMethod(bindPropertyType);
            }
            generator.Emit(OpCodes.Call, method);
            if (method == getValueMethod)
            {
                generator.Emit(OpCodes.Unbox_Any, bindProperty.PropertyType);
            }
            #endregion
        }
Пример #24
0
 private void SetColumns(EntityInfo result)
 {
     foreach (var property in result.Type.GetProperties())
     {
         EntityColumnInfo column = new EntityColumnInfo();
         //var isVirtual = property.GetGetMethod().IsVirtual;
         //if (isVirtual) continue;
         var sugarColumn = property.GetCustomAttributes(typeof(SugarColumn), true)
                           .Where(it => it is SugarColumn)
                           .Select(it => (SugarColumn)it)
                           .FirstOrDefault();
         column.DbTableName  = result.DbTableName;
         column.EntityName   = result.EntityName;
         column.PropertyName = property.Name;
         column.PropertyInfo = property;
         column.UnderType    = UtilMethods.GetUnderType(column.PropertyInfo.PropertyType);
         if (sugarColumn.IsNullOrEmpty())
         {
             column.DbColumnName = property.Name;
         }
         else
         {
             if (sugarColumn.IsJson && String.IsNullOrEmpty(sugarColumn.ColumnDataType))
             {
                 if (this.Context.CurrentConnectionConfig.DbType == DbType.PostgreSQL)
                 {
                     column.DataType = "json";
                 }
                 else
                 {
                     column.DataType = "varchar(4000)";
                 }
             }
             if (sugarColumn.IsIgnore == false)
             {
                 column.DbColumnName       = sugarColumn.ColumnName.IsNullOrEmpty() ? property.Name : sugarColumn.ColumnName;
                 column.IsPrimarykey       = sugarColumn.IsPrimaryKey;
                 column.IsIdentity         = sugarColumn.IsIdentity;
                 column.ColumnDescription  = sugarColumn.ColumnDescription;
                 column.IsNullable         = sugarColumn.IsNullable;
                 column.Length             = sugarColumn.Length;
                 column.OldDbColumnName    = sugarColumn.OldColumnName;
                 column.DataType           = sugarColumn.ColumnDataType;
                 column.DecimalDigits      = sugarColumn.DecimalDigits;
                 column.OracleSequenceName = sugarColumn.OracleSequenceName;
                 column.IsOnlyIgnoreInsert = sugarColumn.IsOnlyIgnoreInsert;
                 column.IsEnableUpdateVersionValidation = sugarColumn.IsEnableUpdateVersionValidation;
                 column.IsTranscoding           = sugarColumn.IsTranscoding;
                 column.SerializeDateTimeFormat = sugarColumn.SerializeDateTimeFormat;
                 column.IsJson              = sugarColumn.IsJson;
                 column.NoSerialize         = sugarColumn.NoSerialize;
                 column.DefaultValue        = sugarColumn.DefaultValue;
                 column.IndexGroupNameList  = sugarColumn.IndexGroupNameList;
                 column.UIndexGroupNameList = sugarColumn.UniqueGroupNameList;
                 column.IsOnlyIgnoreUpdate  = sugarColumn.IsOnlyIgnoreUpdate;
                 column.IsArray             = sugarColumn.IsArray;
             }
             else
             {
                 column.IsIgnore          = true;
                 column.NoSerialize       = sugarColumn.NoSerialize;
                 column.ColumnDescription = sugarColumn.ColumnDescription;
             }
         }
         if (this.Context.MappingColumns.HasValue())
         {
             var golbalMappingInfo = this.Context.MappingColumns.FirstOrDefault(it => it.EntityName.Equals(result.EntityName, StringComparison.CurrentCultureIgnoreCase) && it.PropertyName == column.PropertyName);
             if (golbalMappingInfo != null)
             {
                 column.DbColumnName = golbalMappingInfo.DbColumnName;
             }
         }
         if (this.Context.IgnoreColumns.HasValue())
         {
             var golbalMappingInfo = this.Context.IgnoreColumns.FirstOrDefault(it => it.EntityName.Equals(result.EntityName, StringComparison.CurrentCultureIgnoreCase) && it.PropertyName == column.PropertyName);
             if (golbalMappingInfo != null)
             {
                 column.IsIgnore = true;
             }
         }
         if (this.Context.CurrentConnectionConfig.ConfigureExternalServices != null && this.Context.CurrentConnectionConfig.ConfigureExternalServices.EntityService != null)
         {
             this.Context.CurrentConnectionConfig.ConfigureExternalServices.EntityService(property, column);
         }
         result.Columns.Add(column);
     }
 }
Пример #25
0
        public virtual void ExistLogic(EntityInfo entityInfo)
        {
            if (entityInfo.Columns.HasValue() && entityInfo.IsDisabledUpdateAll == false)
            {
                //Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Multiple primary keys do not support modifications");

                var tableName = GetTableName(entityInfo);
                var dbColumns = this.Context.DbMaintenance.GetColumnInfosByTableName(tableName);
                ConvertColumns(dbColumns);
                var entityColumns = entityInfo.Columns.Where(it => it.IsIgnore == false).ToList();
                var dropColumns   = dbColumns
                                    .Where(dc => !entityColumns.Any(ec => dc.DbColumnName.Equals(ec.OldDbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                    .Where(dc => !entityColumns.Any(ec => dc.DbColumnName.Equals(ec.DbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                    .ToList();
                var addColumns = entityColumns
                                 .Where(ec => ec.OldDbColumnName.IsNullOrEmpty() || !dbColumns.Any(dc => dc.DbColumnName.Equals(ec.OldDbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                 .Where(ec => !dbColumns.Any(dc => ec.DbColumnName.Equals(dc.DbColumnName, StringComparison.CurrentCultureIgnoreCase))).ToList();
                var alterColumns = entityColumns
                                   .Where(ec => !dbColumns.Any(dc => dc.DbColumnName.Equals(ec.OldDbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                   .Where(ec =>
                                          dbColumns.Any(dc => dc.DbColumnName.Equals(ec.DbColumnName) &&
                                                        ((ec.Length != dc.Length && !UtilMethods.GetUnderType(ec.PropertyInfo).IsEnum() && UtilMethods.GetUnderType(ec.PropertyInfo).IsIn(UtilConstants.StringType)) ||
                                                         ec.IsNullable != dc.IsNullable ||
                                                         IsSamgeType(ec, dc)))).ToList();
                var renameColumns = entityColumns
                                    .Where(it => !string.IsNullOrEmpty(it.OldDbColumnName))
                                    .Where(entityColumn => dbColumns.Any(dbColumn => entityColumn.OldDbColumnName.Equals(dbColumn.DbColumnName, StringComparison.CurrentCultureIgnoreCase)))
                                    .ToList();


                var isMultiplePrimaryKey = dbColumns.Where(it => it.IsPrimarykey).Count() > 1 || entityColumns.Where(it => it.IsPrimarykey).Count() > 1;


                var isChange = false;
                foreach (var item in addColumns)
                {
                    this.Context.DbMaintenance.AddColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item));
                    isChange = true;
                }
                if (entityInfo.IsDisabledDelete == false)
                {
                    foreach (var item in dropColumns)
                    {
                        this.Context.DbMaintenance.DropColumn(tableName, item.DbColumnName);
                        isChange = true;
                    }
                }
                foreach (var item in alterColumns)
                {
                    this.Context.DbMaintenance.UpdateColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item));
                    isChange = true;
                }
                foreach (var item in renameColumns)
                {
                    this.Context.DbMaintenance.RenameColumn(tableName, item.OldDbColumnName, item.DbColumnName);
                    isChange = true;
                }

                foreach (var item in entityColumns)
                {
                    var dbColumn = dbColumns.FirstOrDefault(dc => dc.DbColumnName.Equals(item.DbColumnName, StringComparison.CurrentCultureIgnoreCase));
                    if (dbColumn == null)
                    {
                        continue;
                    }
                    bool pkDiff, idEntityDiff;
                    KeyAction(item, dbColumn, out pkDiff, out idEntityDiff);
                    if (dbColumn != null && pkDiff && !idEntityDiff && isMultiplePrimaryKey == false)
                    {
                        var isAdd = item.IsPrimarykey;
                        if (isAdd)
                        {
                            this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName);
                        }
                        else
                        {
                            this.Context.DbMaintenance.DropConstraint(tableName, string.Format("PK_{0}_{1}", tableName, item.DbColumnName));
                        }
                    }
                    else if ((pkDiff || idEntityDiff) && isMultiplePrimaryKey == false)
                    {
                        ChangeKey(entityInfo, tableName, item);
                    }
                }
                if (isMultiplePrimaryKey)
                {
                    var oldPkNames = dbColumns.Where(it => it.IsPrimarykey).Select(it => it.DbColumnName.ToLower()).OrderBy(it => it).ToList();
                    var newPkNames = entityColumns.Where(it => it.IsPrimarykey).Select(it => it.DbColumnName.ToLower()).OrderBy(it => it).ToList();
                    if (!Enumerable.SequenceEqual(oldPkNames, newPkNames))
                    {
                        Check.Exception(true, ErrorMessage.GetThrowMessage("Modification of multiple primary key tables is not supported. Delete tables while creating", "不支持修改多主键表,请删除表在创建"));
                    }
                }
                if (isChange && IsBackupTable)
                {
                    this.Context.DbMaintenance.BackupTable(tableName, tableName + DateTime.Now.ToString("yyyyMMddHHmmss"), MaxBackupDataRows);
                }
            }
        }
Пример #26
0
 public object FormatValue(object value, string name)
 {
     if (value == null)
     {
         return("NULL");
     }
     else
     {
         string N    = this.Context.GetN();
         var    type = UtilMethods.GetUnderType(value.GetType());
         if (type == UtilConstants.StringType && value.ToString().Contains("{SugarSeq:=}"))
         {
             return(value.ToString().Replace("{SugarSeq:=}", ""));
         }
         if (type == UtilConstants.DateType)
         {
             var date = value.ObjToDate();
             if (date < Convert.ToDateTime("1900-1-1"))
             {
                 date = Convert.ToDateTime("1900-1-1");
             }
             return("to_timestamp('" + date.ToString("yyyy-MM-dd HH:mm:ss.ffffff") + "', 'YYYY-MM-DD HH24:MI:SS.FF') ");
         }
         else if (type.IsEnum())
         {
             return(Convert.ToInt64(value));
         }
         else if (type == UtilConstants.ByteArrayType)
         {
             string bytesString = "0x" + BitConverter.ToString((byte[])value).Replace("-", "");
             return(bytesString);
         }
         else if (type == UtilConstants.BoolType)
         {
             return(value.ObjToBool() ? "1" : "0");
         }
         else if (type == UtilConstants.DateTimeOffsetType)
         {
             var date = UtilMethods.ConvertFromDateTimeOffset((DateTimeOffset)value);
             return("to_timestamp('" + date.ToString("yyyy-MM-dd HH:mm:ss.ffffff") + "', 'YYYY-MM-DD HH24:MI:SS.FF') ");
         }
         else if (type == UtilConstants.StringType || type == UtilConstants.ObjType)
         {
             if (value.ToString().Length > 2000)
             {
                 ++i;
                 var parameterName = this.Builder.SqlParameterKeyWord + name + i;
                 this.Parameters.Add(new SugarParameter(parameterName, value));
                 return(parameterName);
             }
             else
             {
                 return(N + "'" + value.ToString().ToSqlFilter() + "'");
             }
         }
         else
         {
             return(N + "'" + value.ToString() + "'");
         }
     }
 }
Пример #27
0
        private Dictionary <string, object> DataReaderToList <T>(IDataReader reader, Type tType, List <PropertyInfo> classProperties, List <T> reval)
        {
            var readerValues = DataReaderToDictionary(reader, tType);
            var result       = new Dictionary <string, object>();

            foreach (var item in classProperties)
            {
                var name     = item.Name;
                var typeName = tType.Name;
                if (item.PropertyType.IsClass())
                {
                    if (IsJsonItem(readerValues, name))
                    {
                        result.Add(name, DeserializeObject <Dictionary <string, object> >(readerValues.First().Value.ObjToString()));
                    }
                    else if (IsJsonList(readerValues, item))
                    {
                        result.Add(name, DeserializeObject <List <Dictionary <string, object> > >(readerValues[item.Name.ToLower()].ToString()));
                    }
                    else
                    {
                        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.First(it => it.Key.Equals(name, StringComparison.CurrentCultureIgnoreCase)).Value;
                        if (addValue == DBNull.Value || addValue == null)
                        {
                            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 if (item.PropertyType == UtilConstants.StringType)
                            {
                                addValue = null;
                            }
                            else
                            {
                                addValue = null;
                            }
                        }
                        else if (item.PropertyType == UtilConstants.IntType)
                        {
                            addValue = Convert.ToInt32(addValue);
                        }
                        else if (UtilMethods.GetUnderType(item.PropertyType) == UtilConstants.LongType)
                        {
                            addValue = Convert.ToInt64(addValue);
                        }
                        result.Add(name, addValue);
                    }
                }
            }

            return(result);
        }
Пример #28
0
        public KeyValuePair <string, SugarParameter[]> ConditionalModelToSql(List <IConditionalModel> models, int beginIndex = 0)
        {
            if (models.IsNullOrEmpty())
            {
                return(new KeyValuePair <string, SugarParameter[]>());
            }
            StringBuilder         builder    = new StringBuilder();
            List <SugarParameter> parameters = new List <SugarParameter>();
            var sqlBuilder = InstanceFactory.GetSqlbuilder(this.Context.CurrentConnectionConfig);
            var mainIndex  = 0;
            var indexTree  = 0;

            foreach (var model in models)
            {
                if (model is ConditionalModel)
                {
                    var item = model as ConditionalModel;
                    if (item.FieldName == $"[value=sql{UtilConstants.ReplaceKey}]")
                    {
                        builder.Append(item.FieldValue);
                        continue;
                    }
                    var index = mainIndex + beginIndex;
                    var type  = index == 0 ? "" : "AND";
                    if (beginIndex > 0)
                    {
                        type = null;
                    }
                    string temp          = " {0} {1} {2} {3}  ";
                    string parameterName = string.Format("{0}Condit{1}{2}", sqlBuilder.SqlParameterKeyWord, item.FieldName, index);
                    if (parameterName.Contains("."))
                    {
                        parameterName = parameterName.Replace(".", "_");
                    }
                    if (parameterName.Contains("["))
                    {
                        parameterName = parameterName.Replace("[", "_");
                    }
                    if (parameterName.Contains("]"))
                    {
                        parameterName = parameterName.Replace("]", "_");
                    }
                    if (parameterName.Contains(this.SqlTranslationLeft))
                    {
                        parameterName = parameterName.Replace(this.SqlTranslationLeft, "_");
                    }
                    string oldName = item.FieldName;
                    item.FieldName = GetTranslationColumnName(item.FieldName);
                    switch (item.ConditionalType)
                    {
                    case ConditionalType.Equal:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "=", parameterName);
                        parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
                        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, GetFieldValue(item)));
                        break;

                    case ConditionalType.GreaterThanOrEqual:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), ">=", parameterName);
                        parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
                        break;

                    case ConditionalType.LessThan:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<", parameterName);
                        parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
                        break;

                    case ConditionalType.LessThanOrEqual:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "<=", parameterName);
                        parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
                        break;

                    case ConditionalType.In:
                        if (item.FieldValue == null)
                        {
                            item.FieldValue = string.Empty;
                        }
                        var inValue1 = ("(" + item.FieldValue.Split(',').ToJoinSqlInVals() + ")");
                        if (item.CSharpTypeName.HasValue() && UtilMethods.IsNumber(item.CSharpTypeName))
                        {
                            inValue1 = inValue1.Replace("'", "");
                        }
                        else if (inValue1.Contains("'null'"))
                        {
                            inValue1 = inValue1.Replace("'null'", "null");
                        }
                        else if (inValue1.Contains("[null]"))
                        {
                            inValue1 = inValue1.Replace("[null]", "null");
                        }
                        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() + ")");
                        if (item.CSharpTypeName.HasValue() && UtilMethods.IsNumber(item.CSharpTypeName))
                        {
                            inValue2 = inValue2.Replace("'", "");
                        }
                        else if (inValue2.Contains("'null'"))
                        {
                            inValue2 = inValue2.Replace("'null'", "null");
                        }
                        else if (inValue2.Contains("[null]"))
                        {
                            inValue2 = inValue2.Replace("[null]", "null");
                        }
                        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.NoLike:
                        builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), " NOT 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.EqualNull:
                        if (GetFieldValue(item) == null)
                        {
                            builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "  IS ", " NULL ");
                        }
                        else
                        {
                            builder.AppendFormat(temp, type, item.FieldName.ToSqlFilter(), "=", parameterName);
                            parameters.Add(new SugarParameter(parameterName, GetFieldValue(item)));
                        }
                        break;

                    case ConditionalType.InLike:
                        var           array = (item.FieldValue + "").Split(',').ToList();
                        List <string> sqls  = new List <string>();
                        int           i     = 0;
                        foreach (var val in array)
                        {
                            var itemParameterName = $"{ parameterName}{index}{i}";
                            sqls.Add(item.FieldName.ToSqlFilter() + " LIKE " + itemParameterName);
                            parameters.Add(new SugarParameter(itemParameterName, "%" + val + "%"));
                            i++;
                        }
                        builder.Append($" {type} ({string.Join(" OR ", sqls)}) ");
                        break;

                    default:
                        break;
                    }
                    item.FieldName = oldName;
                }
                else if (model is ConditionalCollections)
                {
                    var item = model as ConditionalCollections;
                    if (item != null && item.ConditionalList.HasValue())
                    {
                        foreach (var con in item.ConditionalList)
                        {
                            var index   = item.ConditionalList.IndexOf(con);
                            var isFirst = index == 0;
                            var isLast  = index == (item.ConditionalList.Count - 1);
                            if (models.IndexOf(item) == 0 && index == 0 && beginIndex == 0)
                            {
                                builder.AppendFormat(" ( ");
                            }
                            else if (isFirst)
                            {
                                builder.AppendFormat(" {0} ( ", con.Key.ToString().ToUpper());
                            }
                            List <IConditionalModel> conModels = new List <IConditionalModel>();
                            conModels.Add(con.Value);
                            var childSqlInfo = ConditionalModelToSql(conModels, 1000 * (1 + index) + models.IndexOf(item));
                            if (!isFirst && con.Value.FieldName != $"[value=sql{UtilConstants.ReplaceKey}]")
                            {
                                builder.AppendFormat(" {0} ", con.Key.ToString().ToUpper());
                            }
                            builder.Append(childSqlInfo.Key);
                            parameters.AddRange(childSqlInfo.Value);
                            if (isLast)
                            {
                                builder.Append(" ) ");
                            }
                            else
                            {
                            }
                        }
                    }
                }
                else
                {
                    var item = model as ConditionalTree;
                    BuilderTree(builder, item, ref indexTree, parameters, ref mainIndex);
                }
                mainIndex++;
            }
            return(new KeyValuePair <string, SugarParameter[]>(builder.ToString(), parameters.ToArray()));
        }
        private void Update(MemberInitExpression expression, ExpressionParameter parameter)
        {
            int i = 0;

            foreach (MemberBinding binding in expression.Bindings)
            {
                ++i;
                if (binding.BindingType != MemberBindingType.Assignment)
                {
                    throw new NotSupportedException();
                }
                MemberAssignment memberAssignment = (MemberAssignment)binding;
                var type       = expression.Type;
                var memberName = this.Context.GetDbColumnName(type.Name, memberAssignment.Member.Name);
                var item       = memberAssignment.Expression;

                //Column IsJson Handler
                if (memberAssignment.Member.CustomAttributes != null)
                {
                    var customAttribute = memberAssignment.Member.GetCustomAttribute <SugarColumn>();

                    if (customAttribute?.IsJson ?? false)
                    {
                        var paramterValue = ExpressionTool.DynamicInvoke(item);
                        var parameterName = AppendParameter(new SerializeService().SerializeObject(paramterValue));
                        this.Context.Result.Append(base.Context.GetEqString(memberName, parameterName));

                        continue;
                    }
                }

                if ((item is MemberExpression) && ((MemberExpression)item).Expression == null)
                {
                    var    paramterValue = ExpressionTool.DynamicInvoke(item);
                    string parameterName = AppendParameter(paramterValue);
                    this.Context.Result.Append(base.Context.GetEqString(memberName, parameterName));
                }
                else if (IsNotMember(item))
                {
                    if (base.Context.Result.IsLockCurrentParameter == false)
                    {
                        base.Context.Result.CurrentParameter       = parameter;
                        base.Context.Result.IsLockCurrentParameter = true;
                        parameter.IsAppendTempDate();
                        base.Expression = item;
                        base.Expression = (item as UnaryExpression).Operand;
                        base.Start();
                        parameter.IsAppendResult();
                        var result = this.Context.DbMehtods.IIF(new MethodCallExpressionModel()
                        {
                            Args = new List <MethodCallExpressionArgs>()
                            {
                                new MethodCallExpressionArgs()
                                {
                                    IsMember = true, MemberName = parameter.CommonTempData.ObjToString() + "=1"
                                },
                                new MethodCallExpressionArgs()
                                {
                                    IsMember = true, MemberName = AppendParameter(0)
                                },
                                new MethodCallExpressionArgs()
                                {
                                    IsMember = true, MemberName = AppendParameter(1)
                                }
                            }
                        });
                        parameter.Context.Result.Append(base.Context.GetEqString(memberName, result));
                        base.Context.Result.CurrentParameter = null;
                    }
                }
                else if (IsNotParameter(item))
                {
                    try
                    {
                        parameter.Context.Result.Append(base.Context.GetEqString(memberName, AppendParameter(ExpressionTool.DynamicInvoke(item).ObjToBool())));
                    }
                    catch
                    {
                        throw new NotSupportedException(item.ToString());
                    }
                }
                else if (IsMethod(item))
                {
                    if (item is UnaryExpression)
                    {
                        item = (item as UnaryExpression).Operand;
                    }
                    var callMethod = item as MethodCallExpression;
                    if (MethodTimeMapping.Any(it => it.Key == callMethod.Method.Name) || MethodMapping.Any(it => it.Key == callMethod.Method.Name) || IsExtMethod(callMethod.Method.Name) || IsSubMethod(callMethod) || callMethod.Method.DeclaringType.FullName.StartsWith(UtilConstants.AssemblyName + UtilConstants.Dot))
                    {
                        MethodCall(parameter, memberName, item);
                    }
                    else
                    {
                        var    paramterValue = ExpressionTool.DynamicInvoke(item);
                        string parameterName = AppendParameter(paramterValue);
                        this.Context.Result.Append(base.Context.GetEqString(memberName, parameterName));
                    }
                }
                else if (IsConst(item) && IsConvert(item) && UtilMethods.IsNullable(item.Type) && UtilMethods.GetUnderType(item.Type) == UtilConstants.BoolType)
                {
                    item = (item as UnaryExpression).Operand;
                    parameter.Context.Result.Append(base.Context.GetEqString(memberName, GetNewExpressionValue(item)));
                }
                else if (IsConst(item))
                {
                    base.Expression = item;
                    base.Start();
                    string parameterName = this.Context.SqlParameterKeyWord + ExpressionConst.Const + this.Context.ParameterIndex;
                    parameter.Context.Result.Append(base.Context.GetEqString(memberName, parameterName));
                    var addItem  = new SugarParameter(parameterName, parameter.CommonTempData);
                    var dataType = UtilMethods.GetUnderType(item.Type);
                    if (addItem.Value == null && dataType == UtilConstants.DateType)
                    {
                        addItem.DbType = System.Data.DbType.Date;
                    }
                    this.Context.Parameters.Add(addItem);
                    this.Context.ParameterIndex++;
                }
                else if (item is MemberExpression)
                {
                    if (base.Context.Result.IsLockCurrentParameter == false)
                    {
                        base.Context.Result.CurrentParameter       = parameter;
                        base.Context.Result.IsLockCurrentParameter = true;
                        parameter.IsAppendTempDate();
                        base.Expression = item;
                        base.Start();
                        parameter.IsAppendResult();
                        parameter.Context.Result.Append(base.Context.GetEqString(memberName, parameter.CommonTempData.ObjToString()));
                        base.Context.Result.CurrentParameter = null;
                    }
                }
                else if (item is BinaryExpression)
                {
                    var result = GetNewExpressionValue(item);
                    if (result.HasValue())
                    {
                        result = result.Replace(",", UtilConstants.ReplaceCommaKey);
                    }
                    this.Context.Result.Append(base.Context.GetEqString(memberName, result));
                }
                else if (item is MemberInitExpression)
                {
                    try
                    {
                        var value         = ExpressionTool.DynamicInvoke(item);
                        var parameterName = AppendParameter(value);
                        parameter.Context.Result.Append(base.Context.GetEqString(memberName, parameterName));
                    }
                    catch (Exception ex)
                    {
                        throw new NotSupportedException("Not Supported " + item.ToString() + " " + ex.Message);
                    }
                }
                else if (item is NewExpression)
                {
                    try
                    {
                        var value         = ExpressionTool.DynamicInvoke(item);
                        var parameterName = AppendParameter(value);
                        parameter.Context.Result.Append(base.Context.GetEqString(memberName, parameterName));
                    }
                    catch (Exception ex)
                    {
                        throw new NotSupportedException("Not Supported " + item.ToString() + " " + ex.Message);
                    }
                }
                else if (item is ConditionalExpression)
                {
                    var result = GetNewExpressionValue(item);
                    this.Context.Result.Append(base.Context.GetEqString(memberName, result));
                }
            }
        }
Пример #30
0
 public virtual void RepairReplicationParameters(ref string appendSql, SugarParameter[] parameters, int addIndex)
 {
     UtilMethods.RepairReplicationParameters(ref appendSql, parameters, addIndex);
 }