在這個過 程中,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");