分享下自己一直用的.NET SQLSERVER 封装类下自己写的DataHelper 操作类

一,概述:

这个DataHelper 类是基于我上个博客里发的SQLDataAccess 这个类做的一个简单的封装,为了结合自己的实体类和数据操作而产生的。

这里面用了  属性类,反射。还有 数据类型的方法扩展。(入门的同学可以看看。)

这里面有几个地方要注意下,一个是 GetEntity<T> 方法里的 ModelDataAttribute 对象,是我自己写的一个实体属性类。

还有 connString.IsNullOrEmpty() 这个是我封装的一个Stirng 的扩展类(StringExtensions)里的方法。这两个类在下面可以找到。

这个DataHelper类,必须基于 SQLDataAccess 和我自己定义的实体类的形式才可以实现。 这里大家只是借鉴下就好了.

yeqw.FrameWork;  我把 ModelDataAttribute StringExtensions 封装到里面了。

二:代码:

DataHelper:(这里写的不是太好,其中的分页只是调用一个分页存储过程。这个Helper里最大的一个问题,就是不支持事务,一直没考虑好怎么把事务封进来)

  1 namespace yeqw.DataHelper
  2 {
  3     using System;
  4     using System.Collections.Generic;
  5     using System.Data;
  6     using System.Data.SqlClient;
  7     using System.Reflection;
  8     using System.Runtime.InteropServices;
  9     using System.Text.RegularExpressions;
 10     using yeqw.FrameWork;
 11     using yeqw.sql.common.DB;
 12 
 13     public class DBHelper
 14     {
 15         public static int DbExecuteNonQuery(SqlCommand Command)
 16         {
 17             using (SQLDataAccess access = new SQLDataAccess())
 18             {
 19                 return access.ExecuteNonQuery(Command);
 20             }
 21         }
 22 
 23         public static int DbExecuteNonQuery(SqlCommand Command, string connString)
 24         {
 25             using (SQLDataAccess access = new SQLDataAccess(connString))
 26             {
 27                 return access.ExecuteNonQuery(Command);
 28             }
 29         }
 30 
 31         public static object DbExecuteScalar(SqlCommand Command)
 32         {
 33             SQLDataAccess access = new SQLDataAccess();
 34             return access.ExecuteScalar(Command);
 35         }
 36 
 37         public static DataTable ExecProc_sp_GetPage(string tbName, string colName, int coltype, string orderby, string collist, int pagesize, int page, string condition, out int pages, out int rsCount, out int curCount)
 38         {
 39             return ExecProc_sp_GetPage(tbName, colName, coltype, orderby, collist, pagesize, page, condition, out pages, out rsCount, out curCount, "");
 40         }
 41 
 42         public static DataTable ExecProc_sp_GetPage(string tbName, string colName, int coltype, string orderby, string collist, int pagesize, int page, string condition, out int pages, out int rsCount, out int curCount, string connstring)
 43         {
 44             SQLDataAccess access = null;
 45             DataTable table;
 46             if (connstring.IsNullOrEmpty())
 47             {
 48                 access = new SQLDataAccess();
 49             }
 50             else
 51             {
 52                 access = new SQLDataAccess(connstring);
 53             }
 54             try
 55             {
 56                 SqlCommand command = GetCommand(tbName, colName, coltype, orderby, collist, pagesize, page, condition);
 57                 DataSet ds = new DataSet();
 58                 access.FillDataSet(command, ds);
 59                 pages = (int)command.Parameters["@pages"].Value;
 60                 rsCount = (int)command.Parameters["@rsCount"].Value;
 61                 curCount = (int)command.Parameters["@curCount"].Value;
 62                 table = ds.Tables[1];
 63             }
 64             catch (Exception exception)
 65             {
 66                 throw new Exception(exception.Message);
 67             }
 68             finally
 69             {
 70                 access.Dispose();
 71             }
 72             return table;
 73         }
 74 
 75        
 76         public static List<T> FillData<T>(SqlCommand Command) where T : class, new()
 77         {
 78             return FillData<T>(Command, string.Empty);
 79         }
 80 
 81         public static List<T> FillData<T>(SqlCommand Command, string connString) where T : class, new()
 82         {
 83             List<T> list = new List<T>();
 84             SQLDataAccess access = null;
 85             if (connString.IsNullOrEmpty())
 86             {
 87                 access = new SQLDataAccess();
 88             }
 89             else
 90             {
 91                 access = new SQLDataAccess(connString);
 92             }
 93             try
 94             {
 95                 SqlDataReader reader = access.ExecuteReader(Command);
 96                 while (reader.Read())
 97                 {
 98                     T entity = Activator.CreateInstance<T>();
 99                     list.Add(GetEntity<T>(reader, entity));
100                 }
101                 if (!reader.IsClosed)
102                 {
103                     reader.Close();
104                 }
105             }
106             finally
107             {
108                 access.Dispose();
109             }
110             return list;
111         }
112 
113         public static T FillObject<T>(SqlCommand Command) where T : class, new()
114         {
115             return FillObject<T>(Command, string.Empty);
116         }
117 
118         public static T FillObject<T>(SqlCommand Command, string connString) where T : class, new()
119         {
120             SQLDataAccess access = null;
121             if (connString.IsNullOrEmpty())
122             {
123                 access = new SQLDataAccess();
124             }
125             else
126             {
127                 access = new SQLDataAccess(connString);
128             }
129             SqlDataReader reader = null;
130             try
131             {
132                 reader = access.ExecuteReader(Command);
133                 if (reader.Read())
134                 {
135                     return GetEntity<T>(reader, Activator.CreateInstance<T>());
136                 }
137             }
138             finally
139             {
140                 if (!reader.IsClosed)
141                 {
142                     reader.Close();
143                 }
144                 access.Dispose();
145             }
146             return default(T);
147         }
148 
149         private static SqlCommand GetCommand(string tbName, string colName, int coltype, string orderby, string collist, int pagesize, int page, string condition)
150         {
151             string cmdText = "sp_GetPage";
152             SqlCommand command = new SqlCommand(cmdText)
153             {
154                 CommandTimeout = 0,
155                 CommandType = CommandType.StoredProcedure
156             };
157             command.Parameters.Add("@tbName", SqlDbType.VarChar, 100);
158             command.Parameters["@tbName"].Value = tbName;
159             command.Parameters.Add("@colName", SqlDbType.VarChar, 100);
160             command.Parameters["@colName"].Value = colName;
161             command.Parameters.Add("@coltype", SqlDbType.Int, 4);
162             command.Parameters["@coltype"].Value = coltype;
163             command.Parameters.Add("@orderby", SqlDbType.VarChar, 100);
164             command.Parameters["@orderby"].Value = orderby;
165             command.Parameters.Add("@collist", SqlDbType.VarChar, 800);
166             command.Parameters["@collist"].Value = collist;
167             command.Parameters.Add("@pagesize", SqlDbType.Int, 4);
168             command.Parameters["@pagesize"].Value = pagesize;
169             command.Parameters.Add("@page", SqlDbType.Int, 4);
170             command.Parameters["@page"].Value = page;
171             command.Parameters.Add("@condition", SqlDbType.VarChar, 0x7d0);
172             command.Parameters["@condition"].Value = condition;
173             command.Parameters.Add("@pages", SqlDbType.Int);
174             command.Parameters.Add("@rsCount", SqlDbType.Int);
175             command.Parameters.Add("@curCount", SqlDbType.Int);
176             command.Parameters["@pages"].Direction = ParameterDirection.Output;
177             command.Parameters["@rsCount"].Direction = ParameterDirection.Output;
178             command.Parameters["@curCount"].Direction = ParameterDirection.Output;
179             return command;
180         }
181 
182         public static DataSet GetDataSet(SqlCommand Command)
183         {
184             SQLDataAccess access = new SQLDataAccess();
185             DataSet ds = new DataSet();
186             try
187             {
188                 access.FillDataSet(Command, ds);
189             }
190             finally
191             {
192                 access.Dispose();
193             }
194             return ds;
195         }
196 
197         public static DataTable GetDataTable(SqlCommand Command)
198         {
199             SQLDataAccess access = new SQLDataAccess();
200             DataTable table = null;
201             try
202             {
203                 table = new DataTable();
204                 table = access.FillDataSet(Command);
205             }
206             finally
207             {
208                 access.Dispose();
209             }
210             return table;
211         }
212 
213         public static DataTable GetDataTable(SqlCommand Command, string connString)
214         {
215             SQLDataAccess access = new SQLDataAccess(connString);
216             DataTable table = null;
217             try
218             {
219                 table = new DataTable();
220                 table = access.FillDataSet(Command);
221             }
222             finally
223             {
224                 access.Dispose();
225             }
226             return table;
227         }
228 
229         public static DataTable GetDataTableSchema(string TableName)
230         {
231             string cmdText = string.Format("select * from {0} where 1=2", TableName);
232             SQLDataAccess access = new SQLDataAccess();
233             DataTable table = null;
234             try
235             {
236                 SqlCommand command = new SqlCommand(cmdText);
237                 table = new DataTable();
238                 table = access.FillDataSet(command);
239             }
240             finally
241             {
242                 access.Dispose();
243             }
244             return table;
245         }
246 
247         public static DateTime GetDate()
248         {
249             DateTime now = DateTime.Now;
250             string sql = "SELECT getdate()";
251             using (SQLDataAccess access = new SQLDataAccess())
252             {
253                 SqlDataReader reader = access.ExecuteReader(sql);
254                 if (reader.Read())
255                 {
256                     now = (DateTime)reader[0];
257                 }
258                 if (!reader.IsClosed)
259                 {
260                     reader.Close();
261                 }
262             }
263             return now;
264         }
265 
266         public static T GetEntity<T>(IDataReader reader, T entity)
267         {
268             PropertyInfo[] properties = entity.GetType().GetProperties();
269             foreach (PropertyInfo info in properties)
270             {
271                 object[] customAttributes = info.GetCustomAttributes(true);
272                 if (customAttributes.Length != 0)
273                 {
274                     ModelDataAttribute attribute = (ModelDataAttribute)customAttributes[0];
275                     if (!(reader[attribute.SQLFieldName] is DBNull))
276                     {
277                         info.SetValue(entity, reader[attribute.SQLFieldName], null);
278                     }
279                 }
280             }
281             return entity;
282         }
283 
284         public static SqlParameter GetSqlParamseter(string parameterName, object Value)
285         {
286             return GetSqlParamseter(parameterName, SqlDbType.NVarChar, 0, Value);
287         }
288 
289         public static SqlParameter GetSqlParamseter(string parameterName, SqlDbType dbType, int size, ParameterDirection Direction)
290         {
291             SqlParameter parameter = new SqlParameter
292             {
293                 ParameterName = parameterName,
294                 SqlDbType = dbType,
295                 Direction = Direction
296             };
297             if (size != 0)
298             {
299                 parameter.Size = size;
300             }
301             return parameter;
302         }
303 
304         public static SqlParameter GetSqlParamseter(string parameterName, SqlDbType dbType, int size, object Value)
305         {
306             SqlParameter parameter = new SqlParameter
307             {
308                 ParameterName = parameterName,
309                 SqlDbType = dbType
310             };
311             if (((Value == null) || string.IsNullOrEmpty(Value.ToString())) || ((parameter.SqlDbType == SqlDbType.DateTime) && (DateTime.MinValue == Convert.ToDateTime(Value))))
312             {
313                 parameter.Value = DBNull.Value;
314             }
315             else
316             {
317                 parameter.Value = Value;
318             }
319             if (size != 0)
320             {
321                 parameter.Size = size;
322             }
323             return parameter;
324         }
325 
326         public static void SetDBCommandParameters(SqlCommand Comm, object entity)
327         {
328             Comm.Parameters.RemoveAt(0);
329             if (Comm.Parameters.Count > 0)
330             {
331                 PropertyInfo[] properties = entity.GetType().GetProperties();
332                 foreach (SqlParameter parameter in Comm.Parameters)
333                 {
334                     bool flag = false;
335                     foreach (PropertyInfo info in properties)
336                     {
337                         object[] customAttributes = info.GetCustomAttributes(typeof(ModelDataAttribute), true);
338                         if (customAttributes.Length != 0)
339                         {
340                             ModelDataAttribute attribute = (ModelDataAttribute)customAttributes[0];
341                             if (string.Equals(attribute.SQLFieldName, parameter.ParameterName.Replace("@", ""), StringComparison.CurrentCultureIgnoreCase))
342                             {
343                                 object obj2 = info.GetValue(entity, null);
344                                 parameter.SqlDbType = attribute.SQLDbType;
345                                 parameter.Size = attribute.SQLSize;
346                                 parameter.Direction = attribute.SQLParameterDirection;
347                                 if (obj2 != null)
348                                 {
349                                     parameter.Value = obj2;
350                                 }
351                                 else
352                                 {
353                                     parameter.Value = DBNull.Value;
354                                 }
355                                 flag = true;
356                                 break;
357                             }
358                         }
359                     }
360                     if (!flag)
361                     {
362                         throw new Exception("没有找到参数值!");
363                     }
364                 }
365             }
366         }
367 
368         public static void SetSqlParameters(SqlCommand comm, object entity)
369         {
370             comm.Parameters.Clear();
371             string commandText = comm.CommandText;
372             PropertyInfo[] properties = entity.GetType().GetProperties();
373             foreach (PropertyInfo info in properties)
374             {
375                 object[] customAttributes = info.GetCustomAttributes(typeof(ModelDataAttribute), true);
376                 if (customAttributes.Length >= 1)
377                 {
378                     ModelDataAttribute attribute = customAttributes[0] as ModelDataAttribute;
379                     if (Regex.IsMatch(commandText, "@" + attribute.SQLFieldName + @"\b", RegexOptions.Singleline | RegexOptions.IgnoreCase))
380                     {
381                         object obj2 = info.GetValue(entity, null);
382                         SqlParameter parameter = comm.CreateParameter();
383                         parameter.SqlDbType = attribute.SQLDbType;
384                         parameter.ParameterName = "@" + attribute.SQLFieldName;
385                         parameter.Size = attribute.SQLSize;
386                         parameter.Direction = attribute.SQLParameterDirection;
387                         parameter.Value = (obj2 == null) ? DBNull.Value : obj2;
388                         comm.Parameters.Add(parameter);
389                     }
390                 }
391             }
392         }
393 
394         public static int UpdateDataTable(string TableName, DataTable dataTable)
395         {
396             SQLDataAccess access = new SQLDataAccess();
397             SqlCommand selectCommand = new SqlCommand(string.Format("select * from {0} where 1=2", TableName));
398             return access.UpdateDataTable(selectCommand, dataTable);
399         }
400     }
401 }
View Code

 实体类:

 1 using System;
 2 using System.Data;
 3 using yeqw.FrameWork;
 4 using System.ComponentModel;
 5 
 6 namespace yeqw.bm.Model
 7 {
 8     /// <summary>
 9     /// Summary description for adminmenuinfo
10     /// </summary>
11     [Serializable]
12     public class AdminMenuInfo
13     {
14         /// <summary>
15         /// 流水号
16         /// </summary>
17         [ModelData("ID", SqlDbType.Int, 4, ParameterDirection.InputOutput)]
18         public int ID
19         {
20             set;
21             get;
22         }
23         /// <summary>
24         /// 用户流水号
25         /// </summary>
26         [ModelData("AdminID", SqlDbType.Int, 4)]
27         public int AdminID
28         {
29             set;
30             get;
31         }
32         /// <summary>
33         /// 菜单权限流水号
34         /// </summary>
35         [ModelData("MenuAuthorityID", SqlDbType.Int, 4)]
36         public int MenuAuthorityID
37         {
38             set;
39             get;
40         }
41 
42         /// <summary>
43         /// 操作员流水号
44         /// </summary>
45         [ModelData("OperAdminID", SqlDbType.Int, 4)]
46         public int OperAdminID
47         {
48             set;
49             get;
50         }
51 
52         /// <summary>
53         /// 操作时间
54         /// </summary>
55         [ModelData("OperTime", SqlDbType.DateTime, 8)]
56         public DateTime OperTime
57         {
58             set;
59             get;
60         }
61 
62         /// <summary>
63         /// 角色菜单权限状态(0 冻结 1 正常,2关闭)
64         /// </summary>
65         [ModelData("Status", SqlDbType.TinyInt, 1)]
66         public byte Status
67         {
68             set;
69             get;
70         }
71         /// <summary>
72         /// 入库时间
73         /// </summary>
74         [ModelData("InsertTime", SqlDbType.DateTime, 8)]
75         public DateTime InsertTime
76         {
77             set;
78             get;
79         }
80     }
81 }
实体类

StringExtensions 类:

namespace yeqw.FrameWork
{
    using System;
    using System.Runtime.CompilerServices;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Web.Script.Serialization;

    public static class StringExtensions
    {
        public static bool CheckSqlCondition(this string input)
        {
            return true;
        }

        public static object Deserialize(this string base64Str)
        {
            return SerializeHelper.Deserialize(base64Str);
        }

        public static string FormatExtension(this string input, params object[] args)
        {
            return string.Format(input, args);
        }

        public static bool IsALLInteger(this string input)
        {
            return Regex.IsMatch(input, @"^([-]\d+)|\d+$");
        }

        public static bool IsAZaz09(this string input)
        {
            return Regex.IsMatch(input, "^[A-Za-z0-9]+$");
        }

        public static bool IsByte(this string input)
        {
            byte num;
            return byte.TryParse(input, out num);
        }

        public static bool IsChinese(this string input)
        {
            return Regex.IsMatch(input, "^([一-龥]|[︰-ᅠ])+$");
        }

        public static bool IsDecimal(this string input)
        {
            decimal num;
            return decimal.TryParse(input, out num);
        }

        public static bool IsEmail(this string input)
        {
            return Regex.IsMatch(input, @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$");
        }

        public static bool IsEnglish(this string input)
        {
            return Regex.IsMatch(input, "^[a-zA-Z]+$");
        }

        public static bool IsIdCard(this string input)
        {
            string str;
            string str2;
            string str3 = "10x98765432";
            int[] numArray = new int[] { 
                7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 
                2
             };
            string[] strArray = new string[] { 
                "", "", "", "", "", "", "", "", "", "", "", "北京", "天津", "河北", "山西", "内蒙古", 
                "", "", "", "", "", "辽宁", "吉林", "黑龙江", "", "", "", "", "", "", "", "上海", 
                "江苏", "浙江", "安微", "福建", "江西", "山东", "", "", "", "河南", "湖北", "湖南", "广东", "广西", "海南", "", 
                "", "", "重庆", "四川", "贵州", "云南", "西藏", "", "", "", "", "", "", "陕西", "甘肃", "青海", 
                "宁夏", "新疆", "", "", "", "", "", "台湾", "", "", "", "", "", "", "", "", 
                "", "香港", "澳门", "", "", "", "", "", "", "", "", "国外"
             };
            Match match = Regex.Match(input, @"^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[xX\d])))$");
            if (match.Length == 0)
            {
                return false;
            }
            if ((int.Parse(match.Result("$1")) >= strArray.Length) || (strArray[int.Parse(match.Result("$1"))] == ""))
            {
                return false;
            }
            if (match.Result("$2").Length == 12)
            {
                str2 = input.Substring(0, 0x11);
                str = string.Format("{0}-{1}-{2}", match.Result("$9"), match.Result("$10"), match.Result("$11"));
            }
            else
            {
                str2 = input.Substring(0, 6) + "19" + input.Substring(6);
                str = string.Format("19{0}-{1}-{2}", match.Result("$4"), match.Result("$5"), match.Result("$6"));
            }
            try
            {
                DateTime.Parse(str);
            }
            catch (Exception)
            {
                return false;
            }
            int num = 0;
            for (int i = 0; i <= 0x10; i++)
            {
                num += int.Parse(str2.Substring(i, 1)) * numArray[i];
            }
            str2 = str2 + str3.Substring(num % 11, 1);
            return ((input.Length == 15) || ((input.Length == 0x12) && (input == str2)));
        }

        public static bool IsInteger(this string input)
        {
            return Regex.IsMatch(input, "^[0-9]+$");
        }

        public static bool IsIP(this string input)
        {
            return Regex.IsMatch(input, @"^(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5]).(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5]).(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5]).(0|[1-9]\d?|[0-1]\d{2}|2[0-4]\d|25[0-5])$");
        }

        public static bool IsNullOrEmpty(this string input)
        {
            return string.IsNullOrEmpty(input);
        }

        public static bool IsPhone(this string input)
        {
            return Regex.IsMatch(input, @"^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$");
        }

        public static bool IsUrl(this string input)
        {
            return Regex.IsMatch(input, "^http:\\/\\/[A-Za-z0-9\\./=\\?%\\-&_~`@[\\]\\':+!]+([^<>\"])+$");
        }

        public static string NoHTML(this string Htmlstring)
        {
            Htmlstring = Regex.Replace(Htmlstring, "<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(iexcl|#161);", "\x00a1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(cent|#162);", "\x00a2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(pound|#163);", "\x00a3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, "&(copy|#169);", "\x00a9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring = Htmlstring.Replace("<", "");
            Htmlstring = Htmlstring.Replace(">", "");
            Htmlstring = Htmlstring.Replace("\r\n", "");
            Htmlstring = Htmlstring.Replace("&hellip;", "");
            Htmlstring = Htmlstring.Replace("&mdash;", "");
            Htmlstring = Htmlstring.Replace("&rdquo;", "");
            Htmlstring = Htmlstring.Replace("&ldquo;", "");
            return Htmlstring;
        }

        public static string SubStringCN(this string stringToSub, int length, string flage)
        {
            if (stringToSub.IsNullOrEmpty())
            {
                return string.Empty;
            }
            Regex regex = new Regex("[一-龥]+", RegexOptions.Compiled);
            char[] chArray = stringToSub.ToCharArray();
            int byteCount = Encoding.Default.GetByteCount(stringToSub);
            StringBuilder builder = new StringBuilder();
            string str = string.Empty;
            int num2 = 0;
            for (int i = 0; i < byteCount; i++)
            {
                if (i >= chArray.Length)
                {
                    return str;
                }
                if (regex.IsMatch(chArray[i].ToString()))
                {
                    num2 += 2;
                }
                else
                {
                    num2++;
                }
                builder.Append(chArray[i]);
                if (num2 > length)
                {
                    return (builder.ToString(0, builder.ToString().Length - 1) + flage);
                }
                str = builder.ToString();
            }
            return str;
        }

        public static int ToByte(this string input)
        {
            return byte.Parse(input);
        }

        public static decimal ToDecimal(this string input)
        {
            return decimal.Parse(input);
        }

        public static long ToInt64(this string input)
        {
            return long.Parse(input);
        }

        public static int ToInteger(this string input)
        {
            return int.Parse(input);
        }

        public static T ToObject<T>(this string input) where T: class, new()
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Deserialize<T>(input);
        }

        public static bool Validate(this string input, string parrtern)
        {
            return Regex.IsMatch(input, parrtern);
        }
    }
}
View Code

ModelDataAttribute 类:

namespace yeqw.FrameWork
{
    using System;
    using System.Data;
    using System.Runtime.CompilerServices;

    [AttributeUsage(AttributeTargets.Property, Inherited=true)]
    public class ModelDataAttribute : Attribute
    {
        public ModelDataAttribute(string sqlFieldName, SqlDbType sqlParameterType) : this(sqlFieldName, sqlParameterType, 0)
        {
        }

        public ModelDataAttribute(string sqlFieldName, SqlDbType sqlParameterType, int sqlparametersize) : this(sqlFieldName, sqlParameterType, sqlparametersize, ParameterDirection.Input)
        {
        }

        public ModelDataAttribute(string sqlFieldName, SqlDbType sqlParameterType, int sqlparametersize, ParameterDirection sqlParameterDirection)
        {
            this.SQLFieldName = sqlFieldName;
            this.SQLDbType = sqlParameterType;
            this.SQLSize = sqlparametersize;
            this.SQLParameterDirection = sqlParameterDirection;
        }

        public void Validate(object value)
        {
            if (!this.CanNull && string.IsNullOrEmpty(value.ToString()))
            {
                throw new ArgumentException(this.Message);
            }
        }

        public bool CanNull { get; set; }

        public string Message { get; set; }

        public SqlDbType SQLDbType { get; set; }

        public string SQLFieldName { get; set; }

        public ParameterDirection SQLParameterDirection { get; set; }

        public int SQLSize { get; set; }

        public enum EnumValidateType : byte
        {
            IsMaxLength = 2,
            IsNull = 0,
            IsNumber = 1
        }
    }
}
View Code

三:总结:

  DataHepler 和SQLDataAccess 这两个类都是比较简单的一个类库设计。做任何项目适合自己的才是最好的。用CodeSmith 这样的工具都能生成很好的只要的类库。

但我希望大家尤其是刚入门的童鞋要明白,基础才是一切的根本。知其然更要致其所以然。在编程的路上遇到不同的级别的项目,尤其现在都说的大数据时代。任何的类库

都是有自己的局限性的。只有因地制宜,根据实际需要做出自己最合理的选择才是王道。不仅要举一翻三,更要一通百通。类库是死的人是活的,不管是什么样的技术,明白

基础了,才是最重要的。(自己的一点感慨,瞎喷的。呵呵)

================================================================= 
HI,如果童鞋们觉得本人此博文对你有用,请不要吝啬自己的鼠标,给此博文一个“推荐”吧。鼓励,鼓励。哈哈 

本博文系博主原创,版权归博主所有,如需转载,请注明转载地址。

当前博客原始地址:yeqw1985.cnblogs.com 

=================================================================

新浪微博 http://www.weibo.com/yeqw  热烈欢迎大家一起交流讨论并提出宝贵意见,多多指导。
posted @ 2013-11-22 19:52  Kevin Ye  阅读(2684)  评论(3编辑  收藏  举报