C#发现之旅:基于反射和动态编译的快速ORM框架(上)
2010-09-30 21:08:28 来源:WEB开发网在这个过程中,GetFieldIndexs函数提供了一个映射表,而自动生成的代码就是利用这个映射表将数据从DataReader复制到DB_Employees的属性中。
我们自动生成代码实现了InnerReadRecord函数后,在ORM框架中就可以调用基础的RecordORMHelper中的ReadRecord函数读取一行数据并生成一个实体对象,而函数ReadRecords是ReadRecord的另外一个读取多个数据的版本。
根据上述设计,我们可以使用以下代码来生成InnerReadRecord代码
myWriter.WriteLine("// 从数据读取器读取数据创建对象");
myWriter.WriteLine("protected override object InnerReadRecord( System.Data.IDataReader reader , int[] FieldIndexs )");
myWriter.BeginGroup("{");
myWriter.WriteLine( RecordType.FullName + " record = new " + RecordType.FullName + "();");
myWriter.WriteLine("int index = 0 ;");
// 获得类型中绑定到数据库的属性信息
for( int iCount = 0 ; iCount < ps.Length ; iCount ++ )
{
System.Reflection.PropertyInfo p = ps[ iCount ] ;
if( p.CanWrite == false )
{
continue ;
}
BindFieldAttribute fa = ( BindFieldAttribute ) Attribute.GetCustomAttribute(
p , typeof( BindFieldAttribute ));
myWriter.WriteLine("");
myWriter.WriteLine("index = FieldIndexs[ " + iCount + " ]; // 读取字段 " + GetBindFieldName( p ));
myWriter.WriteLine("if( index >= 0 )");
myWriter.BeginGroup("{");
Type pt = p.PropertyType ;
object DefaultValue = this.GetDefaultValue( p );
string strRead = null;
if( pt.Equals( typeof( byte )))
{
strRead = "ConvertToByte( reader.GetValue( index ) , " + GetValueString( pt , DefaultValue ) + ")";
}
else if( pt.Equals( typeof( sbyte )))
{
strRead = "ConvertToSByte( reader.GetValue( index ) , " + GetValueString( pt , DefaultValue ) + ")";
}
else if( pt.Equals( typeof( short )))
{
strRead = "ConvertToInt16( reader.GetValue( index ) , " + GetValueString( pt , DefaultValue ) + ")";
}
处理其他数据类型……
else if( pt.Equals( typeof( DateTime )))
{
string strDefault = "DateTime.MinValue" ;
DateTime dt = Convert.ToDateTime( DefaultValue );
if( dt.Equals( DateTime.MinValue ) == false )
{
strDefault = "new DateTime( " + dt.Ticks + ")";
}
strRead = "ConvertToDateTime( reader.GetValue( index ) , " + strDefault + " , " + ( fa.ReadFormat == null ? "null" : "\"" + fa.ReadFormat + "\"" ) + " )";
}
else if( pt.Equals( typeof( string )))
{
strRead = "ConvertToString( reader.GetValue( index ) , " + ( DefaultValue == null ? "null" : "@\"" + DefaultValue.ToString() + "\"" ) + " )";
}
else if( pt.Equals( typeof( char )))
{
strRead = "ConvertToChar( reader.GetValue( index ) , " + GetValueString( pt , DefaultValue ) + " )";
}
else
{
throw new InvalidOperationException("不支持属性类型" + p.Name + " " + pt.FullName );
}
myWriter.WriteLine("record." + p.Name + " = " + strRead + " ;" );
myWriter.EndGroup("}");
}//for
myWriter.WriteLine("");
myWriter.WriteLine("return record ;");
myWriter.EndGroup(")//InnerReadRecord");
更多精彩
赞助商链接