代码
----DataReader转换为实体的泛型类---
注意 数据库表字段名和实体类相同
public class EntityTranslate
{
/// 用class关键字表示约束为引用类型
/// 用struct关键字表示约束为值类型
/// new()默认构造函数约束:如果需要在泛型类型内部实例化类型参数的对象,
///就必须对类型参数加以默认构造函数约束,除此之外别无选择。
//执行查询返回对象集合
public static List<TEntity> Translate<TEntity>(IDataReader reader) where TEntity : class, new()
{
List<TEntity> list = new List<TEntity>();
Type entityType = typeof(TEntity);
//创建实例
object entity = Activator.CreateInstance(entityType);
List<string> attributes = new List<string>();
Dictionary<string, PropertyInfo> dic = new Dictionary<string, PropertyInfo>();
foreach (PropertyInfo info in entityType.GetProperties())
{
dic.Add(info.Name, info);
}
string columnName = string.Empty;
//object[] attributes = info.GetCustomAttributes(true);
while (reader.Read())
{
TEntity t = new TEntity();
foreach (KeyValuePair<string, PropertyInfo> attribute in dic)
{
columnName = attribute.Key;
int filedIndex = 0;
while (filedIndex < reader.FieldCount)
{
if (reader.GetName(filedIndex) == columnName)
{
attribute.Value.SetValue(t, reader[filedIndex], null);
break;
}
filedIndex++;
}
}
list.Add(t);
}
return list;
}
}
实现代码:
public void ReaderToEntity()
{
string sql = "select * from T_User";
IDataReader reader = DAO.GetReader(sql);
List<User> list = EntityTranslate.Translate<User>(reader);
foreach (User user in list)
{
Console.WriteLine("用户ID:" + user.Id.ToString() + " 用户名:"
+ user.UserName + " 密码:" + user.UserPwd);
}
reader.Close();
}
注意 数据库表字段名和实体类相同
public class EntityTranslate
{
/// 用class关键字表示约束为引用类型
/// 用struct关键字表示约束为值类型
/// new()默认构造函数约束:如果需要在泛型类型内部实例化类型参数的对象,
///就必须对类型参数加以默认构造函数约束,除此之外别无选择。
//执行查询返回对象集合
public static List<TEntity> Translate<TEntity>(IDataReader reader) where TEntity : class, new()
{
List<TEntity> list = new List<TEntity>();
Type entityType = typeof(TEntity);
//创建实例
object entity = Activator.CreateInstance(entityType);
List<string> attributes = new List<string>();
Dictionary<string, PropertyInfo> dic = new Dictionary<string, PropertyInfo>();
foreach (PropertyInfo info in entityType.GetProperties())
{
dic.Add(info.Name, info);
}
string columnName = string.Empty;
//object[] attributes = info.GetCustomAttributes(true);
while (reader.Read())
{
TEntity t = new TEntity();
foreach (KeyValuePair<string, PropertyInfo> attribute in dic)
{
columnName = attribute.Key;
int filedIndex = 0;
while (filedIndex < reader.FieldCount)
{
if (reader.GetName(filedIndex) == columnName)
{
attribute.Value.SetValue(t, reader[filedIndex], null);
break;
}
filedIndex++;
}
}
list.Add(t);
}
return list;
}
}
实现代码:
public void ReaderToEntity()
{
string sql = "select * from T_User";
IDataReader reader = DAO.GetReader(sql);
List<User> list = EntityTranslate.Translate<User>(reader);
foreach (User user in list)
{
Console.WriteLine("用户ID:" + user.Id.ToString() + " 用户名:"
+ user.UserName + " 密码:" + user.UserPwd);
}
reader.Close();
}