Welcome

首页 / 软件开发 / C# / C#发现之旅第十一讲 使用反射和特性构造自己的ORM框架(下)

C#发现之旅第十一讲 使用反射和特性构造自己的ORM框架(下)2011-04-27 cnblogs 袁永福在InnerReadValue函数中遍历所有的属性绑定信息,调用IDataReader.GetValue函数从数据库中获得原始数据,然后调用FieldBindInfo.FromDataBase函数对这个原始数据进行一些处理,主要是进行格式化和数据类型转换,然后调用PropertyInfo.SetValue函数根据读取的数据设置对象实例的属性值。这样遍历了所有的绑定信息也就完整的填充了对象实例的属性值。

在ReadObjects函数中,遍历所有查询的数据,对每个记录创建一个对象实例,遍历数据库记录完毕后,我们就将所有创建的对象实例组成一个数组作为函数返回值,然后退出函数。

我们可以在这个ReadObjects函数上面派生出一系列的从数据库读取对象的函数。这个ReadObjects函数就实现了框架程序读取数据这个核心功能之一。

此外我们还定义了一个Contains函数用于判断一个应用程序对象实例对应的数据库记录是否存在。

新增数据

框架程序的InsertObjects函数就能将若干个对象插入的数据库表中。其主要代码为

/// <summary>
/// 将若干个对象插入到数据库中
/// </summary>
/// <param name="Objects">对象列表</param>
/// <param name="TableName">制定的数据表,若未指定则使用默认的数据表名</param>
/// <returns>插入的数据库记录的个数</returns>
public int InsertObjects( System.Collections.IEnumerable Objects , string TableName )
{
if( Objects == null )
{
throw new ArgumentNullException("Objects");
}
this.CheckBindInfo( Objects , false );
System.Collections.ArrayList list = new System.Collections.ArrayList();
foreach( object obj in Objects )
{
list.Add( obj );
}
if( list.Count == 0 ){
return 0 ;
}
this.CheckConnetion();
// 上一次执行的SQL语句
string strLastSQL = null ;
int InsertCount = 0 ;
using( System.Data.IDbCommand cmd = myConnection.CreateCommand())
{
foreach( object obj in list )
{
TableBindInfo table = this.GetBindInfo( obj.GetType());
string TableName2 = TableName ;
if( TableName2 == null || TableName.Trim().Length == 0 )
{
TableName2 = table.TableName ;
}
System.Collections.ArrayList values = new System.Collections.ArrayList();
// 拼凑SQL语句
System.Text.StringBuilder myStr = new System.Text.StringBuilder();
System.Text.StringBuilder myFields = new System.Text.StringBuilder();
foreach( FieldBindInfo field in table.Fields )
{
if( field.Property.CanRead == false )
{
throw new Exception("属性 " + field.Property.Name + " 是不可写的");
}
object v = field.Property.GetValue( obj , null );
if( v == null || DBNull.Value.Equals( v ))
{
continue ;
}
values.Add( field.ToDataBase( v ));
if( myStr.Length > 0 )
{
myStr.Append(" , ");
myFields.Append( " , " );
}
myStr.Append(" ? " );
myFields.Append( FixFieldName( field.FieldName ));
}//foreach
myStr.Insert( 0 , "Insert Into " + FixTableName( TableName2 )
+" ( " + myFields.ToString() + " ) Values ( " );
myStr.Append( " ) " );
string strSQL = myStr.ToString();
if( strSQL != strLastSQL )
{
// 重新设置SQL命令对象
strLastSQL = strSQL ;
cmd.Parameters.Clear();
cmd.CommandText = strSQL ;
for( int iCount = 0 ; iCount < values.Count ; iCount ++ )
{
cmd.Parameters.Add( cmd.CreateParameter());
}
}
// 填充SQL命令参数值
for( int iCount = 0 ; iCount < values.Count ; iCount ++ )
{
( ( System.Data.IDbDataParameter ) cmd.Parameters[ iCount ]).Value = values[ iCount ] ;
}
// 执行SQL命令向数据表新增记录
InsertCount += cmd.ExecuteNonQuery();
}//foreach
}//using
return InsertCount ;
}