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

2014-11-24 11:47:20 · 作者: · 浏览: 68
对象
tableInfo.TableName = GetTableName(type);//获取表名
//获取属性信息数组
PropertyInfo[] properties = ReflectionUtils.GetProperties(type);
foreach (PropertyInfo property in properties)
{
object propvalue = null;//属性值
string columnName = string.Empty;//列名( 数据库表结构)
string propName = columnName = property.Name;//属性名称
//如果不是做查询操作,获取属性值
if(dbOpType != DbOperateType.SELECT)
propvalue = ReflectionUtils.GetPropertyValue(entity, property);
//获取实体对象属性自定义属性数组(如Column、Id、Table)
object[] propertyAttrs = property.GetCustomAttributes(false);
for (int i = 0; i < propertyAttrs.Length; i++)
{
object propertyAttr = propertyAttrs[i];
//判断是否忽略列,即不插入或更新到数据库中(IsInsert=false、IsUpdate=false)
if (DbEntityUtils.IsCaseColumn(propertyAttr, dbOpType))
break;
//获取Column自定义属性中配置的Name值(表的列名)
string tempName = GetColumnName(propertyAttr);
//如果属性上未配置Column或Column上未配置Name,则取属性名称作为列名
columnName = tempName == string.Empty propName : tempName;
//判断自定义属性是否为Id
if (propertyAttr is IdAttribute)
{
if (dbOpType == DbOperateType.INSERT)
{
if (CommonUtils.IsNullOrEmpty(propvalue))
{
//获取主键生成方式,存入tableInfo.Strategy属性中
IdAttribute idAttr = propertyAttr as IdAttribute;
tableInfo.Strategy = idAttr.Strategy;
//如果是插入操作,且主键ID值为空,则根据主键生成策略生成主键值,
//默认生成策略为自动增长,这种情况不处理,有数据库来处理
strPrimaryKey = DbEntityUtils.GetPrimaryKey(propertyAttr);
if (!string.IsNullOrEmpty(strPrimaryKey))
propvalue = strPrimaryKey;
}
}
//将列名,属性值加入到tableInfo的Id对象中
tableInfo.Id.Key = columnName;
tableInfo.Id.Value = propvalue;
//将列名、属性名作对应关系,保存于tableInfo.PropToColumn中,以作后用
tableInfo.PropToColumn.Put(propName, columnName);
breakForeach = true;//如果为Id,则跳出Foreach循环
}
}
//如果breakForeach=true跳出进入下一次循环continue
if (breakForeach) { breakForeach = false; continue; }
//将列名、属性值加入到tableInfo.Columns中
tableInfo.Columns.Put(columnName, propvalue);
//将属性名、列名作对应关系,以作后用
tableInfo.PropToColumn.Put(propName, columnName);
}
return tableInfo;
}
在代码1-3中用到了获取实体对象中自定义属性所配置的表名、列名代码分别为1-5:
public static string GetTableName(Type classType)
{
string strTableName = string.Empty;
string strEntityName = string.Empty;
strEntityName = classType.FullName;
object classAttr = classType.GetCustomAttributes(false)[0];
if (classAttr is TableAttribute)
{
TableAttribute tableAttr = classAttr as TableAttribute;
strTableName = tableAttr.Name;
}
if (string.IsNullOrEmpty(strTableName))
{
throw new Exception("实体类:" + strEntityName + "的属性配置[Table(name=\"tablename\")]错误或未配置");
}
re