实战 .Net 数据访问层 - 21

(2) EntityConvert

这个东东是模仿 System.Convert 的产物,刚开始没觉得咋样,用起来还真有点舍不得呢(本文开头的代码 1 中曾经使用过这个 Utility )!

不信,且看如下代码(仅举两例 J ):

代码 16 :我变,我变,我变变变!

public static class ** EntityConvert **

{

public static ** IList ** ToList( ** DbDataReader ** rdr, ** Type ** entity)

{

** ArrayList ** list = new ** ArrayList ** ();

using (rdr)

{

while (rdr.Read())

{

object obj = ToObject(rdr, entity, false );

if (obj != null )

list.Add(obj);

}

}

return list;

}

public static object ToObject( ** DbDataReader ** rdr,

** Type ** entity, bool bNeedRead)

{

object obj = null ;

if (!bNeedRead || rdr.Read())

{

// 创建 Data Entity 对象

obj = ** Activator ** .CreateInstance(entity);

// 设置 Data Entity 对象之字段数据

** FieldInfo ** [] fields = entity.GetFields(

** BindingFlags ** .Instance | ** BindingFlags ** .Public);

foreach ( ** FieldInfo ** field in fields)

{

string fieldName = field.Name;

object fieldValue = rdr[fieldName];

if (fieldValue == System. ** DBNull ** .Value)

field.SetValue(obj, null );

else

field.SetValue(obj, fieldValue);

}

if (bNeedRead && !rdr.Read())

rdr.Close();

}

return obj;

}

}


下一段: http://www.csdn.net/develop/Read_Article.asp?id=27566

Published At
Categories with Web编程
Tagged with
comments powered by Disqus