记录一下动态生sqlParameter[]

生成SqlParameter[]

 public class DbParameterGenerator
    {
        /// <summary>
        /// 根据方法的参数获取sqlparameter
        /// </summary>
        /// <param name="method">方法对像</param>
        /// <param name="values">参数对应的值</param>
        /// <returns></returns>
        public static System.Data.SqlClient.SqlParameter[] GetParameterGenerator(System.Reflection.MethodInfo method, object[] values)
        {

            if (method == null)
            {
                method = (MethodInfo)new System.Diagnostics.StackTrace().GetFrame(1).GetMethod();
            }
            ParameterInfo[] param = method.GetParameters();
            SqlParameter[] sqlParam = new SqlParameter[values.Length];
            int count = 0;
            for (int i = 0; i < param.Length; i++)
            {
                if (Attribute.IsDefined(param[i], typeof(NoDataFiledAttribute)))
                {
                    continue;
                }
                DataFiledAttribute d = Attribute.GetCustomAttribute(param[i], typeof(DataFiledAttribute)) as DataFiledAttribute;
                SqlParameter sparam = null;
                if (d.FieldName.StartsWith("@"))
                {
                    sparam = new SqlParameter(d.FieldName, values[count]);
                }
                else
                {
                    sparam = new SqlParameter("@" + d.FieldName, values[count]);

                }
                sqlParam[count] = sparam;
                count++;
            }
            return sqlParam;
        }

    }

test类:

 public class test
    {
        public static SqlParameter[] TestParam([DataFiled("id", SqlDbType.Int)] int id, [NoDataFiled] int userID)
        {
            SqlParameter[] param = DbParameterGenerator.GetParameterGenerator(MethodInfo.GetCurrentMethod() as MethodInfo, new object[] { id });
            return param;
        }
    }
posted @ 2013-01-17 10:20  ML Guo  阅读(221)  评论(0编辑  收藏  举报