实战 .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