这两天弄竞赛的事情, 于是就遇到一件非常恶心人的事. 就是我们有20+张表, 但是我们每一个表都要有查询, 有的还要有增加和修改. 每个表又有N张字段, 最悲剧的事情是比赛时不能带任何工具, 于是每个表的增删改查都变成了非常繁琐的工作. 于是我就想到了Cocoa里的Key-Value Coding, 我想C#里应该也有差不多的东西, 对那就是和Java一个名字的Reflection!
现在只需要在实体类里把属性的名字和数据库的字段的名字一一对应, 就可以直接用一个函数全都读出来, 省了原来那些没必要的构造函数和从数据库里每读出来一个字段就要写一行代码的过程.
原来要写这样的代码:
string sql = "select * from contacts where u_id=@ContactID"; SqlParameter[] sqlParameters = new SqlParameter[1] { new SqlParameter("@ContactID", contactID), }; DataSet ds = DBManager.DBQuery.ExcuteQuery(sql, sqlParameters); if (ds == null) { return null; } int count = ds.Tables[0].Rows.Count; if (count > 0) { Contact contact = new Contact(ds.Tables[0].Rows[0]["u_id"].ToString(), ds.Tables[0].Rows[0]["u_name"].ToString(), ds.Tables[0].Rows[0]["u_tel"].ToString(), ds.Tables[0].Rows[0]["u_email"].ToString(), ds.Tables[0].Rows[0]["u_photo"].ToString(), ds.Tables[0].Rows[0]["u_accountID"].ToString()); return contact; } return null;
现在只需要这样一个函数, 就能把传进去的类型对应的全部字段读取出来:
public static void CopyProperties(Object obj, DataSet ds) { Type type = obj.GetType(); PropertyInfo[] pi = type.GetProperties(); foreach (PropertyInfo item in pi) { Object value = ds.Tables[0].Rows[0][item.Name.ToLower()]; if (!string.IsNullOrEmpty(value.ToString())) { item.SetValue(obj, value, null); } } }
调用时只需要这样:
public static StudentsContact StudentsContactByID(string studentID) { string sql = "select * from StudentsContacts where s_id=@StudentID"; SqlParameter[] sqlParameters = new SqlParameter[1] { new SqlParameter("@StudentID", studentID), }; DataSet ds = DBManager.DBQuery.ExcuteQuery(sql, sqlParameters); int count = ds.Tables[0].Rows.Count; if (count > 0) { StudentsContact studentContact = new StudentsContact(); Tools.CopyProperties(studentContact, ds); return studentContact; } return null; }