自己动手写ORM框架(六):实现查询功能FindById方法(四)

2014-11-24 11:47:20 · 作者: · 浏览: 71
turn strTableName;
}
上面是获取表名,下面这段代码是获取列名,如下代码1-6:
public static string GetColumnName(object attribute)
{
string columnName = string.Empty;
if (attribute is ColumnAttribute)
{
ColumnAttribute columnAttr = attribute as ColumnAttribute;
columnName = columnAttr.Name;
}
if (attribute is IdAttribute)
{
IdAttribute idAttr = attribute as IdAttribute;
columnName = idAttr.Name;
}
return columnName;
}
1-3中第二行代码:String strSql = DbEntityUtils.GetFindByIdSql(tableInfo);
根据已经存入表信息的对象tableInfo来生成SQL语句,代码1-7:
public static string GetFindByIdSql(TableInfo tableInfo)
{
StringBuilder sbColumns = new StringBuilder();
if (tableInfo.Columns.ContainsKey(tableInfo.Id.Key))
tableInfo.Columns[tableInfo.Id.Key] = tableInfo.Id.Value;
else
tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);
//根据Columns中的keys生成例如"studentid,studentno,name,sex..”字符串
foreach (String key in tableInfo.Columns.Keys)
{
sbColumns.Append(key).Append(",");
}
sbColumns.Remove(sbColumns.ToString().Length - 1, 1);
string strSql = "SELECT {0} FROM {1} WHERE {2} = " + AdoHelper.DbParmChar + "{2}";
strSql = string.Format(strSql, sbColumns.ToString(), tableInfo.TableName, tableInfo.Id.Key);
//得到如strSql=”select studentid,studentno,name,sex.. from student
where studentid=@studentid”;(oracle数据库参数前用:,sqlserver用@)
return strSql;
}
下面是几个工具类代码,ReflectionUtils,根据反射获取或设置对象属性值、DynamicMethodCompiler动态方法编译,可提高反射的性能。
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
namespace System.Orm.Common
{
public class ReflectionUtils
{
public static PropertyInfo[] GetProperties(Type type)
{
return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
public static FieldInfo[] GetFields(Type type)
{
return type.GetFields(BindingFlags.Public | BindingFlags.Instance);
}
public static void SetPropertyValue(object obj, PropertyInfo property, object value)
{
//创建Set委托
SetHandler setter = DynamicMethodCompiler.CreateSetHandler(obj.GetType(),property);
//先获取该私有成员的数据类型
Type type = property.PropertyType;
//通过数据类型转换
value = TypeUtils.ConvertForType(value, type);
//将值设置到对象中
setter(obj, value);
}
public static object GetPropertyValue(object obj, PropertyInfo property)
{
//创建Set委托
GetHandler getter = DynamicMethodCompiler.CreateGetHandler(obj.GetType(), property);
//获取属性值
return getter(obj);
}
public static void SetFieldValue(object obj, FieldInfo field, object value)
{
//创建Set委托
SetHandler setter = DynamicMethodCompiler.CreateSetHandler(obj.GetType(), field);
//先获取该私有成员的数据类型
Type type = field.FieldType;
//通过数据类型转换
value = TypeUtils.ConvertForType(value, type);