DataReader转换为实体的应用

本文介绍了一种使用DataReader将数据库查询结果转换为实体对象集合的通用方法。该方法利用了C#的泛型特性,能够适用于任何实体类,只要实体类的属性名称与数据库字段相匹配。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ExpandedBlockStart.gif代码
 ----DataReader转换为实体的泛型类---
        注意 数据库表字段名和实体类相同
        
public class EntityTranslate
        {
            
/// 用class关键字表示约束为引用类型
            
/// 用struct关键字表示约束为值类型
            
/// new()默认构造函数约束:如果需要在泛型类型内部实例化类型参数的对象,
           
///就必须对类型参数加以默认构造函数约束,除此之外别无选择。
          //执行查询返回对象集合 
          public static List<TEntity> Translate<TEntity>(IDataReader reader) where TEntity : classnew() 
            {
                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();
        }

 

转载于:https://www.cnblogs.com/hubcarl/archive/2010/04/07/1706354.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值