C#基础系列:实现自己的ORM(MiniORM的测试代码)2011-05-29 csdn博客 老田看到有同学反馈,说MiniORM代码有Bug,也不知道怎么用,所以今天我就写了些测试代码。希望能够给点帮助。同时也发现了两Bug,一并罗列出:1、MiniORM.PubFuncs.GetObjectType()函数:
1.public static Type GetObjectType(string assemblyname, string namespacename, string classname)
2.{
3.Type objType = (Type)_HashObjectType[assemblyname + namespacename + classname];
4.
5.if (objType == null)
6.{
7.object obj = _HashObjectType[assemblyname + namespacename + classname];
8.
9.obj = Assembly.Load(assemblyname).CreateInstance(namespacename + "." + classname);
10.
11._HashObjectType[assemblyname + namespacename + classname] = obj.GetType();
12.
13.//需要增加这句
14.objType = (Type)_HashObjectType[assemblyname + namespacename + classname];
15.}
16.
17.return objType;
18.}
2、MiniORM.OrmWriter.CheckValidate()函数:
1.public void CheckValidate(object ModelObject)
2.{
3.PropertyInfo[] infos = ModelObject.GetType().GetProperties();
4.object[] CustomerAttributes = null;
5.object[] CustomerAttributes1 = null;
6.
7.//SELECT ID FROM TableName WHERE @A="" OR @B=""
8.string strSQL = "SELECT ID FROM {0} WHERE {1}";
9.string strTablename = PubFuncs.GetTableName(ModelObject);
10.string strWOA = "";
11.string strWHERE = "";
12.string strFieldMessage = "";
13.
14.foreach (PropertyInfo info in infos)
15.{
16.CustomerAttributes = info.GetCustomAttributes(typeof(MiniORMAttribute.DataFieldNotDoubleAttribute), false);
17.CustomerAttributes1 = info.GetCustomAttributes(typeof(MiniORMAttribute.DataFieldAttribute), false);
18.
19.if (CustomerAttributes != null && CustomerAttributes1 != null)
20.{
21.for (int i = 0; i < CustomerAttributes.Length; i++)
22.{
23.strWHERE += strWOA + ((MiniORMAttribute.DataFieldAttribute)CustomerAttributes1[0]).FieldName + "="" + info.GetValue(ModelObject, null) + """;
24.strFieldMessage += ((MiniORMAttribute.DataFieldAttribute)CustomerAttributes1[0]).FieldName;
25.strWOA = " OR ";
26.}
27.}
28.}
29.
30.//这里需要做strWHERE不为空的判断
31.if (strWHERE.Trim() != "")
32.{
33.strSQL = string.Format(strSQL, new string[] { strTablename, strWHERE });
34.
35.using (SqlConnection conn = new SqlConnection(PubFuncs.ConnectionStr))
36.{
37.conn.Open();
38.SqlCommand cmd = new SqlCommand();
39.cmd.Connection = conn;
40.cmd.CommandType = CommandType.Text;
41.cmd.CommandText = strSQL;
42.
43.using (SqlDataReader rdr = cmd.ExecuteReader())
44.{
45.if (rdr.Read())
46.{
47.throw new Exception("下列字段值不能重复:" + strFieldMessage);
48.}
49.}
50.}
51.}
52.}