コード例 #1
0
        private static void ReadOracle(Object item, DbDataReader dr, int id, PropertyModel info)
        {
            object value    = null;
            var    typeName = dr.GetDataTypeName(id);

            if (string.Compare(typeName, "clob", true) == 0 || string.Compare(typeName, "nclob", true) == 0)
            {
                var temp = BaseEmit.Invoke(dr, dr.GetType().GetMethod("GetOracleClob"), new object[] { id });
                if (temp != null)
                {
                    value = BaseEmit.Get(temp, "Value");
                    BaseEmit.Invoke(temp, temp.GetType().GetMethod("Close"), null);
                    BaseEmit.Invoke(temp, temp.GetType().GetMethod("Dispose"), null);
                }
            }
            else if (string.Compare(typeName, "blob", true) == 0)
            {
                var temp = BaseEmit.Invoke(dr, dr.GetType().GetMethod("GetOracleBlob"), new object[] { id });
                if (temp != null)
                {
                    value = BaseEmit.Get(temp, "Value");
                    BaseEmit.Invoke(temp, temp.GetType().GetMethod("Close"), null);
                    BaseEmit.Invoke(temp, temp.GetType().GetMethod("Dispose"), null);
                }
            }
            else
            {
                value = dr.GetValue(id);
            }

            if (!dr.IsDBNull(id))
            {
                BaseEmit.Set(item, info.Name, value);
            }
        }
コード例 #2
0
        /// <summary>
        /// 泛型特性成员
        /// </summary>
        public static List <ColumnModel> GetAttributesColumnInfo(string tableName, List <PropertyInfo> ListInfo)
        {
            var list = new List <ColumnModel>();

            ListInfo.ForEach(a => {
                var temp      = new ColumnModel();
                temp.Name     = a.Name;
                var paramList = GetPropertyInfo <ColumnModel>(true);

                a.CustomAttributes.ToList().ForEach(b => {
                    if (b.AttributeType.Name == typeof(ColumnAttribute).Name)
                    {
                        b.NamedArguments.ToList().ForEach(c => {
                            if (paramList.Exists(p => string.Compare(p.Name, c.MemberName, true) == 0))
                            {
                                BaseEmit.Set(temp, c.MemberName, c.TypedValue.Value);
                            }
                        });
                    }
                });

                if (temp.IsKey && temp.IsNull)
                {
                    temp.IsNull = false;
                }

                list.Add(temp);
            });

            return(list);
        }
コード例 #3
0
        /// <summary>
        /// 获取datatabel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <returns></returns>
        public static DataTable GetTable <T>(DbCommand cmd, List <T> list)
        {
            var dt = new DataTable();

            cmd.CommandText = string.Format("select top 1 * from {0}", typeof(T).Name);
            dt.Load(cmd.ExecuteReader());
            dt.Clear();
            list.ForEach(p => {
                var row = dt.NewRow();
                PropertyCache.GetPropertyInfo <T>().ForEach(a => { row[a.Name] = BaseEmit.Get <T>(p, a.Name); });
                dt.Rows.Add(row);
            });
            return(dt);
        }
コード例 #4
0
        /// <summary>
        /// model 转 insert sql
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="model">实体</param>
        /// <param name="sql">sql</param>
        /// <param name="oracleParam">参数</param>
        /// <returns></returns>
        public static OptionModel InsertToSql <T>(T model, ConfigModel config)
        {
            var sbName  = new StringBuilder();
            var sbValue = new StringBuilder();
            var list    = new List <MemberInfo>();
            var result  = new OptionModel();

            try
            {
                sbName.AppendFormat("insert into {0} (", typeof(T).Name);
                sbValue.Append(" values (");

                PropertyCache.GetPropertyInfo <T>(config.IsPropertyCache).ForEach(p =>
                {
                    if (!list.Exists(a => a.Name == p.Name))
                    {
                        sbName.AppendFormat("{0},", p.Name);

                        sbValue.AppendFormat("{1}{0},", p.Name, config.Flag);

                        var itemValue      = BaseEmit.Get <T>(model, p.Name);
                        var temp           = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                        temp.ParameterName = p.Name;
                        temp.Value         = itemValue == null ? DBNull.Value : itemValue;
                        result.Param.Add(temp);
                    }
                });

                result.Sql = string.Format("{0}) {1})", sbName.ToString().Substring(0, sbName.ToString().Length - 1)
                                           , sbValue.ToString().Substring(0, sbValue.ToString().Length - 1));
                result.IsSuccess = true;
                return(result);
            }
            catch (Exception ex)
            {
                if (string.Compare(config.SqlErrorType, SqlErrorType.Db, true) == 0)
                {
                    DbLogTable.LogException(config, ex, "InsertToSql<T>", result.Sql);
                }
                else
                {
                    DbLog.LogException(config.IsOutError, config.DbType, ex, "InsertToSql<T>", result.Sql);
                }

                result.IsSuccess = false;
                return(result);
            }
        }
コード例 #5
0
        /// <summary>
        /// mysql
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetMySql <T>(List <T> list)
        {
            var sql = new StringBuilder();

            sql.AppendFormat("insert into {0}(", typeof(T).Name);
            PropertyCache.GetPropertyInfo <T>().ForEach(a => { sql.AppendFormat("{0},", a.Name); });
            sql.Append(")").Replace(",)", ")");
            list.ForEach(a => {
                sql.Append("(");
                PropertyCache.GetPropertyInfo <T>().ForEach(p => {
                    sql.AppendFormat("'{0}',", BaseEmit.Get <T>(a, p.Name));
                });
                sql.Append("),").Replace(",)", ")");
            });

            return(sql.ToStr().Substring(0, sql.ToStr().Length - 1));
        }
コード例 #6
0
ファイル: BaseCodeDom.cs プロジェクト: weizhonzhen/FastData
        public static bool GetResult(string code, string references = null)
        {
            //动态编译
            var compiler = new CSharpCodeProvider().CreateCompiler();
            var param    = new CompilerParameters();

            param.ReferencedAssemblies.Add("System.dll");
            param.ReferencedAssemblies.Add("System.Core.dll");
            param.ReferencedAssemblies.Add("mscorlib.dll");

            var assembly = AppDomain.CurrentDomain.GetAssemblies().ToList().Find(a => a.FullName.Split(',')[0] == references);

            if (assembly == null)
            {
                assembly = Assembly.Load(references);
            }

            param.ReferencedAssemblies.Add(assembly.Location);

            param.GenerateExecutable = false;
            param.GenerateInMemory   = true;
            var result = compiler.CompileAssemblyFromSource(param, GetCode(code, references));

            if (result.Errors.HasErrors)
            {
                var error = new StringBuilder();
                error.AppendFormat("code:{0},error info:", GetCode(code));

                foreach (CompilerError info in result.Errors)
                {
                    error.Append(info.ErrorText);
                }

                BaseLog.SaveLog(error.ToString(), "DynamicCompiler");

                return(false);
            }
            else
            {
                assembly = result.CompiledAssembly;
                var instance = assembly.CreateInstance("DynamicCode.Condition");
                var method   = instance.GetType().GetMethod("OutPut");
                return((bool)BaseEmit.Invoke(instance, method, null));
            }
        }
コード例 #7
0
        /// <summary>
        /// set value
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="item"></param>
        /// <param name="dynSet"></param>
        /// <param name="dr"></param>
        /// <param name="info"></param>
        /// <param name="config"></param>
        private static T SetValue <T>(T item, DbDataReader dr, PropertyModel info, ConfigModel config)
        {
            try
            {
                var colName = config.DbType == DataDbType.Oracle ? info.Name.ToUpper() : info.Name;
                var id      = dr.GetOrdinal(colName);
                if (DataDbType.Oracle == config.DbType)
                {
                    ReadOracle(item, dr, id, info);
                }
                else if (!dr.IsDBNull(id))
                {
                    BaseEmit.Set(item, info.Name, dr.GetValue(id));
                }

                return(item);
            }
            catch { return(item); }
        }
コード例 #8
0
        /// <summary>
        /// 获取datatabel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <returns></returns>
        public static DataTable GetTable(DbCommand cmd, List <object> list, System.Type type)
        {
            var dt = new DataTable();

            cmd.CommandText = string.Format("select top 1 * from {0}", type.Name);
            dt.Load(cmd.ExecuteReader());
            dt.Clear();

            list.ForEach(a =>
            {
                var row = dt.NewRow();
                PropertyCache.GetPropertyInfo(list[0]).ForEach(p =>
                {
                    row[p.Name] = BaseEmit.Get(a, p.Name);
                });
                dt.Rows.Add(row);
            });

            return(dt);
        }
コード例 #9
0
        /// <summary>
        /// 解析表达式
        /// </summary>
        /// <param name="exp"></param>
        /// <param name="isRight"></param>
        /// <returns></returns>
        private static string RouteExpressionHandler(ConfigModel config, Expression exp, ExpressionType expType, ref List <string> leftList, ref List <string> rightList, ref List <System.Type> typeList, ref StringBuilder sb, ref string strType, ref int i, bool isRight = false)
        {
            var isReturnNull = false;

            if (exp is BinaryExpression)
            {
                BinaryExpression be = (BinaryExpression)exp;

                return(BinaryExpressionHandler(config, be.Left, be.Right, be.NodeType, ref leftList, ref rightList, ref typeList, ref sb, ref strType, ref i, isRight));
            }
            else if (exp is MemberExpression)
            {
                if ((exp as MemberExpression).Expression is ParameterExpression)
                {
                    return((exp as MemberExpression).Member.Name);
                }
                else
                {
                    if (Expression.Lambda(exp).Compile().DynamicInvoke() == null)
                    {
                        typeList.Add("".GetType());
                    }
                    else
                    {
                        typeList.Add(Expression.Lambda(exp).Compile().DynamicInvoke().GetType());
                    }
                    return(Expression.Lambda(exp).Compile().DynamicInvoke().ToStr());
                }
            }
            else if (exp is NewArrayExpression)
            {
                NewArrayExpression naExp   = (NewArrayExpression)exp;
                StringBuilder      sbArray = new StringBuilder();
                foreach (Expression expression in naExp.Expressions)
                {
                    sbArray.AppendFormat(",{0}", RouteExpressionHandler(config, expression, expType, ref leftList, ref rightList, ref typeList, ref sb, ref strType, ref i, isRight));
                }

                return(sbArray.Length == 0 ? "" : sbArray.Remove(0, 1).ToString());
            }
            else if (exp is MethodCallExpression)
            {
                if (isRight)
                {
                    typeList.Add(Expression.Lambda(exp).Compile().DynamicInvoke().GetType());
                    return(Expression.Lambda(exp).Compile().DynamicInvoke().ToStr());
                }
                else
                {
                    isRight = false;
                    try
                    {
                        var asName = "";
                        var meExp  = (MethodCallExpression)(exp.ReduceExtensions().Reduce());

                        #region 表别名
                        if (meExp.Object != null)
                        {
                            if (meExp.Object is MemberExpression && (meExp.Object as MemberExpression).Expression is ParameterExpression)
                            {
                                asName = string.Format("{0}.", ((meExp.Object as MemberExpression).Expression as ParameterExpression).Name);
                            }
                            else if (meExp.Object is UnaryExpression)
                            {
                                asName = string.Format("{0}.", (((meExp.Object as UnaryExpression).Operand as MemberExpression).Expression as ParameterExpression).Name);
                            }
                        }
                        #endregion

                        if (meExp.Object is MemberExpression && !string.IsNullOrEmpty(asName))
                        {
                            #region system的方法转sql的系统函数
                            var mMethod = meExp.Method.Name;
                            var mName   = ((MemberExpression)meExp.Object).Member.Name;
                            var mValue  = "";
                            var mStar   = "";
                            var mLength = "";
                            var mCount  = 0;

                            meExp.Arguments.ToList().ForEach(a =>
                            {
                                mCount++;
                                mValue = Expression.Lambda(a).Compile().DynamicInvoke().ToString();

                                if (meExp.Arguments.Count == 2)
                                {
                                    if (mCount == 1)
                                    {
                                        mStar = Expression.Lambda(a).Compile().DynamicInvoke().ToString();
                                    }

                                    if (mCount == 2)
                                    {
                                        mLength = Expression.Lambda(a).Compile().DynamicInvoke().ToString();
                                    }
                                }
                            });

                            if (string.Compare(mMethod, "contains", true) == 0)
                            {
                                sb.AppendFormat(" {2}{0} like {3}{0}{1}", mName, i, asName, config.Flag);
                                leftList.Add(mName);
                                rightList.Add(string.Format("%{0}%", mValue));
                                i++;
                            }
                            else if (string.Compare(mMethod, "endswith", true) == 0)
                            {
                                sb.AppendFormat(" {2}{0} like {3}{0}{1}", mName, i, asName, config.Flag);
                                leftList.Add(mName);
                                rightList.Add(string.Format("%{0}", mValue));
                            }
                            else if (string.Compare(mMethod, "startswith", true) == 0)
                            {
                                sb.AppendFormat(" {2}{0} like {3}{0}{1}", mName, i, asName, config.Flag);
                                leftList.Add(mName);
                                rightList.Add(string.Format("{0}%", mValue));
                                i++;
                            }
                            else if (string.Compare(mMethod, "substring", true) == 0)
                            {
                                var tempType = "";
                                if (expType == ExpressionType.Goto)
                                {
                                    tempType = "=";
                                }
                                else
                                {
                                    tempType = ExpressionTypeCast(expType);
                                }

                                if (config.DbType == DataDbType.SqlServer)
                                {
                                    sb.AppendFormat(" substring({4}{0},{2},{3}) {6} {5}{0}{1}", mName, i, mStar, mLength, asName, config.Flag, tempType);
                                }
                                else if (config.DbType == DataDbType.Oracle || config.DbType == DataDbType.MySql || config.DbType == DataDbType.DB2)
                                {
                                    sb.AppendFormat(" substr({4}{0},{2},{3}) {6} {5}{0}{1}", mName, i, mStar, mLength, asName, config.Flag, tempType);
                                }

                                leftList.Add(mName);
                                i++;
                            }
                            else if (string.Compare(mMethod, "toupper", true) == 0)
                            {
                                var tempType = "";
                                if (expType == ExpressionType.Goto)
                                {
                                    tempType = "=";
                                }
                                else
                                {
                                    tempType = ExpressionTypeCast(expType);
                                }
                                sb.AppendFormat(" upper({0}{1}) {4} {2}{1}{3}", asName, mName, config.Flag, i, tempType);

                                leftList.Add(mName);
                                i++;
                            }
                            else if (string.Compare(mMethod, "CompareTo", true) == 0)
                            {
                                var tempType = "";
                                if (expType == ExpressionType.Goto)
                                {
                                    tempType = "=";
                                }
                                else
                                {
                                    tempType = ExpressionTypeCast(expType);
                                }
                                sb.AppendFormat(" upper({0}{1}) {4} upper({2}{1}{3})", asName, mName, config.Flag, i, tempType);

                                leftList.Add(mName);
                                rightList.Add(mValue.ToString());
                                i++;
                            }
                            else if (string.Compare(mMethod, "tolower", true) == 0)
                            {
                                var tempType = "";
                                if (expType == ExpressionType.Goto)
                                {
                                    tempType = "=";
                                }
                                else
                                {
                                    tempType = ExpressionTypeCast(expType);
                                }
                                sb.AppendFormat(" lower({0}{1}) {4} {2}{1}{3}", asName, mName, config.Flag, i, tempType);

                                leftList.Add(mName);
                                i++;
                            }
                            #endregion
                        }

                        if (meExp.Object == null && meExp.Method.Name == "Contains" && meExp.Arguments.Count == 2)
                        {
                            #region array.Contains
                            var array = Expression.Lambda(meExp.Arguments[0]).Compile().DynamicInvoke() as Array;
                            var mName = (meExp.Arguments[1] as MemberExpression).Member.Name;
                            asName = string.Format("{0}.", ((meExp.Arguments[1] as MemberExpression).Expression as ParameterExpression).Name);

                            sb.AppendFormat(" {0}{1} in (", asName, mName);
                            for (int ary = 0; ary < array.Length; ary++)
                            {
                                sb.AppendFormat("{0}{1}{2},", config.Flag, mName, i);
                                leftList.Add(mName);
                                rightList.Add(array.GetValue(ary).ToStr());
                                i++;
                            }
                            sb.Remove(sb.Length - 1, 1);
                            sb.Append(")");
                            #endregion
                        }

                        if (string.IsNullOrEmpty(asName) && meExp.Method.Name == "Contains" && meExp.Arguments.Count == 1)
                        {
                            #region list.Contains
                            var mName = (meExp.Arguments[0] as MemberExpression).Member.Name;
                            asName = string.Format("{0}.", ((meExp.Arguments[0] as MemberExpression).Expression as ParameterExpression).Name);
                            var model = Expression.Lambda(meExp.Object).Compile().DynamicInvoke();
                            var count = (int)BaseEmit.Invoke(model, model.GetType().GetMethod("get_Count"), null);

                            sb.AppendFormat(" {0}{1} in (", asName, mName);
                            for (var j = 0; j < count; j++)
                            {
                                sb.AppendFormat("{0}{1}{2},", config.Flag, mName, i);
                                leftList.Add(mName);
                                rightList.Add(BaseEmit.Invoke(model, model.GetType().GetMethod("get_Item"), new object[] { j }).ToStr());
                                i++;
                            }
                            sb.Remove(sb.Length - 1, 1);
                            sb.Append(")");
                            #endregion
                        }

                        if (isReturnNull)
                        {
                            return("");
                        }
                        else
                        {
                            return(sb.ToString());
                        }
                    }
                    catch
                    {
                        return("");
                    }
                }
            }
            else if (exp is ConstantExpression)
            {
                typeList.Add("".GetType());
                ConstantExpression cExp = (ConstantExpression)exp;
                if (cExp.Value == null)
                {
                    return("null");
                }
                else
                {
                    return(cExp.Value.ToString());
                }
            }
            else if (exp is UnaryExpression)
            {
                var ue = ((UnaryExpression)exp);
                return(RouteExpressionHandler(config, ue.Operand, expType, ref leftList, ref rightList, ref typeList, ref sb, ref strType, ref i, isRight));
            }

            return(null);
        }
コード例 #10
0
        public object Invoke(object proxy, MethodInfo method, object[] args)
        {
            var pModel = new PageModel();
            var param  = new List <DbParameter>();
            var config = DataConfig.GetConfig();
            var key    = string.Format("{0}.{1}", method.DeclaringType.FullName, method.Name);

            if (DbCache.Exists(config.CacheType, key))
            {
                var model = DbCache.Get <ServiceModel>(config.CacheType, key);

                if (model.isPage)
                {
                    pModel = (PageModel)args.ToList().Find(a => a.GetType() == typeof(PageModel));
                }

                config = DataConfig.GetConfig(model.dbKey);
                if (model.isSysType)
                {
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (args[i].GetType() == typeof(PageModel))
                        {
                            continue;
                        }

                        var temp = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                        temp.ParameterName = model.param.GetValue(i.ToString()).ToStr();
                        temp.Value         = args[i];
                        param.Add(temp);
                    }
                }
                else if (model.isDic)
                {
                    if (!args.ToList().Exists(a => a.GetType() == typeof(Dictionary <string, object>)))
                    {
                        throw new Exception($"error: service {method.DeclaringType.Name} , method {method.Name} , param type {args[0].GetType().Name} is not support");
                    }

                    var dic     = (Dictionary <string, object>)args.ToList().Find(a => a.GetType() == typeof(Dictionary <string, object>));
                    var tempDic = new Dictionary <int, string>();

                    foreach (KeyValuePair <string, object> keyValue in dic)
                    {
                        key = string.Format("{0}{1}", config.Flag, keyValue.Key).ToLower();
                        if (model?.sql.IndexOf(key) > 0 || model.isXml)
                        {
                            tempDic.Add((int)(model?.sql.IndexOf(key)), keyValue.Key);
                        }
                    }
                    var list = tempDic.OrderBy(d => d.Key).ToList();
                    foreach (KeyValuePair <int, string> keyValue in list)
                    {
                        var temp = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                        temp.ParameterName = keyValue.Value;
                        temp.Value         = dic.GetValue(keyValue.Value);
                        param.Add(temp);
                    }
                }
                else
                {
                    var data = args.ToList().Find(a => a.GetType() != typeof(PageModel));
                    var type = method.GetParameters().ToList().Find(a => a.ParameterType != typeof(PageModel)).ParameterType;
                    for (int i = 0; i < model.param.Count; i++)
                    {
                        var temp = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                        temp.ParameterName = model.param.GetValue(i.ToString()).ToStr();
                        temp.Value         = BaseEmit.Get(data, temp.ParameterName);
                        temp.ParameterName = temp.ParameterName.ToLower();
                        param.Add(temp);
                    }
                }

                if (model.isXml)
                {
                    model.sql = MapXml.GetFastMapSql(method, config, ref param);
                }

                using (var db = new DataContext(config.Key))
                {
                    if (model.isWrite)
                    {
                        return(db.ExecuteSql(model.sql, param.ToArray(), Aop.AopType.FaseWrite).writeReturn);
                    }
                    else
                    {
                        return(db.FastReadAttribute(model, param, pModel));
                    }
                }
            }

            throw new Exception($"error: service {method.DeclaringType.Name} , method {method.Name} not exists");
        }
コード例 #11
0
        /// <summary>
        ///  to list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public static IList ToList(System.Type type, Object model, DbDataReader dr, ConfigModel config, List <string> field = null)
        {
            var list    = Activator.CreateInstance(type);
            var colList = new List <string>();

            if (dr == null)
            {
                return(null);
            }

            if (dr.HasRows)
            {
                colList = GetCol(dr);
            }

            var propertyList = PropertyCache.GetPropertyInfo(model, config.IsPropertyCache);

            while (dr.Read())
            {
                var item = Activator.CreateInstance(model.GetType());

                if (field == null || field.Count == 0)
                {
                    foreach (var info in propertyList)
                    {
                        if (!colList.Exists(a => string.Compare(a, info.Name, true) == 0))
                        {
                            continue;
                        }

                        if (info.PropertyType.IsGenericType && info.PropertyType.GetGenericTypeDefinition() != typeof(Nullable <>))
                        {
                            continue;
                        }

                        item = SetValue(item, dr, info, config);
                    }
                }
                else
                {
                    for (var i = 0; i < field.Count; i++)
                    {
                        if (!colList.Exists(a => string.Compare(a, field[i], true) == 0))
                        {
                            continue;
                        }

                        if (propertyList.Exists(a => string.Compare(a.Name, field[i], true) == 0))
                        {
                            var info = propertyList.Find(a => string.Compare(a.Name, field[i], true) == 0);
                            item = SetValue(item, dr, info, config);
                        }
                    }
                }

                list.GetType().GetMethods().ToList().ForEach(m =>
                {
                    if (m.Name == "Add")
                    {
                        BaseEmit.Invoke(list, m, new object[] { item });
                    }
                });
            }

            return((IList)list);
        }
コード例 #12
0
        /// <summary>
        /// model 转 delete sql
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="model"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        public static OptionModel DeleteToSql(DbCommand cmd, object model, ConfigModel config)
        {
            var result = new OptionModel();

            result.IsCache = config.IsPropertyCache;
            var where      = PrimaryKey(config, cmd, model.GetType());

            if (where.Count == 0)
            {
                result.Message   = string.Format("{0}没有主键", model.GetType().Name);
                result.IsSuccess = false;
                return(result);
            }

            try
            {
                result.Sql = string.Format("delete {0} ", model.GetType().Name);

                var count = 1;
                foreach (var item in where)
                {
                    var itemValue = BaseEmit.Get(model, item);

                    if (itemValue == null)
                    {
                        result.IsSuccess = false;
                        result.Message   = string.Format("主键{0}值为空", item);
                        return(result);
                    }

                    if (count == 1)
                    {
                        result.Sql = string.Format("{2} where {0}={1}{0} ", item, config.Flag, result.Sql);
                    }
                    else
                    {
                        result.Sql = string.Format("{2} and {0}={1}{0} ", item, config.Flag, result.Sql);
                    }

                    var temp = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                    temp.ParameterName = item;
                    temp.Value         = itemValue == null ? DBNull.Value : itemValue;

                    result.Param.Add(temp);

                    count++;
                }

                result.IsSuccess = true;

                return(result);
            }
            catch (Exception ex)
            {
                if (config.SqlErrorType == SqlErrorType.Db)
                {
                    DbLogTable.LogException(config, ex, "UpdateToSql", result.Sql);
                }
                else
                {
                    DbLog.LogException(config.IsOutError, config.DbType, ex, "DeleteToSql", result.Sql);
                }
                result.IsSuccess = false;
                return(result);
            }
        }
コード例 #13
0
        /// <summary>
        /// model 转 update list sql
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="model">实体</param>
        /// <param name="sql">sql</param>
        /// <param name="oracleParam">参数</param>
        /// <returns></returns>
        public static OptionModel UpdateListToSql <T>(DbCommand cmd, List <T> list, ConfigModel config, Expression <Func <T, object> > field = null)
        {
            var result = new OptionModel();

            result.IsCache = config.IsPropertyCache;
            var where      = PrimaryKey(config, cmd, typeof(T));

            if (where.Count == 0)
            {
                result.Message   = string.Format("{0}没有主键", typeof(T).Name);
                result.IsSuccess = false;
                return(result);
            }

            try
            {
                result.table = BaseExecute.ToDataTable <T>(cmd, config, where, field);

                result.Sql = string.Format("update {0} set", typeof(T).Name);
                var pInfo = PropertyCache.GetPropertyInfo <T>(config.IsPropertyCache);

                if (field == null)
                {
                    #region 属性
                    foreach (var item in pInfo)
                    {
                        if (where.Exists(a => a == item.Name))
                        {
                            continue;
                        }
                        result.Sql = string.Format("{2} {0}={1}{0},", item.Name, config.Flag, result.Sql);
                        var temp = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                        temp.ParameterName = item.Name;
                        temp.SourceColumn  = item.Name;
                        result.Param.Add(temp);
                    }
                    #endregion
                }
                else
                {
                    #region lambda
                    foreach (var item in (field.Body as NewExpression).Members)
                    {
                        if (where.Exists(a => a == item.Name))
                        {
                            continue;
                        }
                        result.Sql = string.Format("{2} {0}={1}{0},", item.Name, config.Flag, result.Sql);
                        var temp = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                        temp.ParameterName = item.Name;
                        temp.SourceColumn  = item.Name;
                        result.Param.Add(temp);
                    }
                    #endregion
                }

                result.Sql = result.Sql.Substring(0, result.Sql.Length - 1);

                var count = 1;
                where.ForEach(a =>
                {
                    if (count == 1)
                    {
                        result.Sql = string.Format("{2} where {0}={1}{0} ", a, config.Flag, result.Sql);
                    }
                    else
                    {
                        result.Sql = string.Format("{2} and {0}={1}{0} ", a, config.Flag, result.Sql);
                    }

                    var temp           = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                    temp.ParameterName = a;
                    temp.SourceColumn  = a;
                    result.Param.Add(temp);
                    count++;
                });

                result.IsSuccess = true;

                list.ForEach(p =>
                {
                    var row = result.table.NewRow();
                    where.ForEach(a => { row[a] = BaseEmit.Get <T>(p, a); });
                    if (field == null)
                    {
                        PropertyCache.GetPropertyInfo <T>().ForEach(a => { row[a.Name] = BaseEmit.Get <T>(p, a.Name); });
                    }
                    else
                    {
                        (field.Body as NewExpression).Members.ToList().ForEach(a => { row[a.Name] = BaseEmit.Get <T>(p, a.Name); });
                    }
                    result.table.Rows.Add(row);
                });

                return(result);
            }
            catch (Exception ex)
            {
                if (config.SqlErrorType == SqlErrorType.Db)
                {
                    DbLogTable.LogException <T>(config, ex, "UpdateListToSql<T>", result.Sql);
                }
                else
                {
                    DbLog.LogException <T>(config.IsOutError, config.DbType, ex, "UpdateListToSql<T>", result.Sql);
                }

                result.IsSuccess = false;
                return(result);
            }
        }
コード例 #14
0
        /// <summary>
        /// model 转 update sql
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="model">实体</param>
        /// <param name="sql">sql</param>
        /// <param name="oracleParam">参数</param>
        /// <returns></returns>
        public static OptionModel UpdateToSql <T>(T model, ConfigModel config, Expression <Func <T, object> > field = null, DbCommand cmd = null)
        {
            var result = new OptionModel();

            result.IsCache = config.IsPropertyCache;
            var where      = PrimaryKey(config, cmd, typeof(T));

            try
            {
                result.Sql = string.Format("update {0} set", typeof(T).Name);
                if (field == null)
                {
                    #region 属性
                    PropertyCache.GetPropertyInfo <T>(config.IsPropertyCache).ForEach(a =>
                    {
                        result.Sql         = string.Format("{2} {0}={1}{0},", a.Name, config.Flag, result.Sql);
                        var itemValue      = BaseEmit.Get <T>(model, a.Name);
                        var temp           = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                        temp.ParameterName = a.Name;
                        temp.Value         = itemValue == null ? DBNull.Value : itemValue;
                        result.Param.Add(temp);
                    });
                    #endregion
                }
                else
                {
                    #region lambda
                    (field.Body as NewExpression).Members.ToList().ForEach(a =>
                    {
                        result.Sql         = string.Format("{2} {0}={1}{0},", a.Name, config.Flag, result.Sql);
                        var itemValue      = BaseEmit.Get <T>(model, a.Name);
                        var temp           = DbProviderFactories.GetFactory(config.ProviderName).CreateParameter();
                        temp.ParameterName = a.Name;
                        temp.Value         = itemValue == null ? DBNull.Value : itemValue;
                        result.Param.Add(temp);
                    });
                    #endregion
                }

                foreach (var item in where)
                {
                    if (result.Param.Exists(a => a.ParameterName == item))
                    {
                        var itemValue = BaseEmit.Get <T>(model, item);
                        if (itemValue == null)
                        {
                            result.IsSuccess = false;
                            result.Message   = string.Format("主键{0}值为空", item);
                            return(result);
                        }
                    }
                }

                result.Sql       = result.Sql.Substring(0, result.Sql.Length - 1);
                result.IsSuccess = true;

                return(result);
            }
            catch (Exception ex)
            {
                if (string.Compare(config.SqlErrorType, SqlErrorType.Db, true) == 0)
                {
                    DbLogTable.LogException(config, ex, "UpdateToSql<T>", result.Sql);
                }
                else
                {
                    DbLog.LogException(config.IsOutError, config.DbType, ex, "UpdateToSql<T>", result.Sql);
                }

                result.IsSuccess = false;
                return(result);
            }
        }
コード例 #15
0
        /// <summary>
        /// mysql
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetMySql(List <object> list)
        {
            var sql = new StringBuilder();

            sql.AppendFormat("insert into {0}(", list[0].GetType().Name);
            //var dyn = new Property.DynamicGet(list[0]);

            PropertyCache.GetPropertyInfo(list[0]).ForEach(a => { sql.AppendFormat("{0},", a.Name); });

            sql.Append(")").Replace(",)", ")");

            list.ForEach(a =>
            {
                sql.Append("(");
                PropertyCache.GetPropertyInfo(list[0]).ForEach(b => { sql.AppendFormat("'{0}',", BaseEmit.Get(a, b.Name)); }); // dyn.GetValue(a, b.Name)
                sql.Append("),").Replace(",)", ")");
            });

            return(sql.ToStr().Substring(0, sql.ToStr().Length - 1));
        }
コード例 #16
0
        /// <summary>
        /// model 转 update sql
        /// </summary>
        /// <typeparam name="T">泛型</typeparam>
        /// <param name="model">实体</param>
        /// <param name="sql">sql</param>
        /// <param name="oracleParam">参数</param>
        /// <returns></returns>
        public static OptionModel UpdateToSql <T>(DbCommand cmd, T model, ConfigModel config, Expression <Func <T, object> > field = null)
        {
            var result = new OptionModel();

            result.IsCache = config.IsPropertyCache;
            var where      = PrimaryKey(config, cmd, typeof(T));

            if (where.Count == 0)
            {
                result.Message   = string.Format("{0}没有主键", typeof(T).Name);
                result.IsSuccess = false;
                return(result);
            }

            try
            {
                result.Sql = string.Format("update {0} set", typeof(T).Name);
                var pInfo = PropertyCache.GetPropertyInfo <T>(config.IsPropertyCache);

                if (field == null)
                {
                    #region 属性
                    foreach (var item in pInfo)
                    {
                        if (where.Exists(a => a == item.Name))
                        {
                            continue;
                        }

                        result.Sql = string.Format("{2} {0}={1}{0},", item.Name, config.Flag, result.Sql);

                        var itemValue = BaseEmit.Get <T>(model, item.Name);
                        var temp      = DbProviderFactories.GetFactory(config).CreateParameter();
                        temp.ParameterName = item.Name;
                        temp.Value         = itemValue == null ? DBNull.Value : itemValue;
                        result.Param.Add(temp);
                    }
                    #endregion
                }
                else
                {
                    #region lambda
                    var list = (field.Body as NewExpression).Members;
                    foreach (var item in list)
                    {
                        if (where.Exists(a => a == item.Name))
                        {
                            continue;
                        }

                        result.Sql = string.Format("{2} {0}={1}{0},", item.Name, config.Flag, result.Sql);

                        var itemValue = BaseEmit.Get <T>(model, item.Name);
                        var temp      = DbProviderFactories.GetFactory(config).CreateParameter();
                        temp.ParameterName = item.Name;
                        temp.Value         = itemValue == null ? DBNull.Value : itemValue;
                        result.Param.Add(temp);
                    }
                    #endregion
                }

                result.Sql = result.Sql.Substring(0, result.Sql.Length - 1);

                var count = 1;
                foreach (var item in where)
                {
                    var itemValue = BaseEmit.Get <T>(model, item);

                    if (itemValue == null)
                    {
                        result.IsSuccess = false;
                        result.Message   = string.Format("主键{0}值为空", item);
                        return(result);
                    }

                    if (count == 1)
                    {
                        result.Sql = string.Format("{2} where {0}={1}{0} ", item, config.Flag, result.Sql);
                    }
                    else
                    {
                        result.Sql = string.Format("{2} and {0}={1}{0} ", item, config.Flag, result.Sql);
                    }

                    var temp = DbProviderFactories.GetFactory(config).CreateParameter();
                    temp.ParameterName = item;
                    temp.Value         = itemValue == null ? DBNull.Value : itemValue;

                    result.Param.Add(temp);

                    count++;
                }

                result.IsSuccess = true;

                return(result);
            }
            catch (Exception ex)
            {
                if (config.SqlErrorType == SqlErrorType.Db)
                {
                    DbLogTable.LogException <T>(config, ex, "UpdateToSql<T>", result.Sql);
                }
                else
                {
                    DbLog.LogException <T>(config.IsOutError, config.DbType, ex, "UpdateToSql<T>", result.Sql);
                }
                result.IsSuccess = false;
                return(result);
            }
        }