c# 将IDataReader转换为DataTable

本文介绍了一种方法,能够将IDataReader中的数据转换为DataTable或.NET中的具体模型实例。首先,通过遍历IDataReader的所有字段来创建一个DataTable,接着展示了如何将DataReader的数据行映射到指定类型的对象实例中,并提供了将所有数据读取为对象列表的方法。

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

    /// <summary>
    ///  将IDataReader转换为DataTable
    /// </summary>
    /// <param name="reader"></param>
    /// <returns></returns>
    public static DataTable DataTableToIDataReader(IDataReader reader)
    {
        DataTable objDataTable = new DataTable("Table");
        int intFieldCount = reader.FieldCount;
        for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
        {
            objDataTable.Columns.Add(reader.GetName(intCounter).ToUpper(), reader.GetFieldType(intCounter));
        }
        objDataTable.BeginLoadData();
        object[] objValues = new object[intFieldCount];
        while (reader.Read())
        {
            reader.GetValues(objValues);
            objDataTable.LoadDataRow(objValues, true);
        }
        reader.Close();
        objDataTable.EndLoadData();
        return objDataTable;
    }
 
    public static T ReaderToModel<T>(IDataReader dr)
    {
        try
        {
            using (dr)
            {
                if (dr.Read())
                {
                    List<string> list = new List<string>(dr.FieldCount);
                    for (int i = 0; i < dr.FieldCount; i++)
                    {
                        list.Add(dr.GetName(i).ToLower());
                    }
                    T model = Activator.CreateInstance<T>();
                    foreach (PropertyInfo pi in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                    {
                        if (list.Contains(pi.Name.ToLower()))
                        {
                            if (!IsNullOrDBNull(dr[pi.Name]))
                            {
                                pi.SetValue(model, HackType(dr[pi.Name], pi.PropertyType), null);
                            }
                        }
                    }
                    return model;
                }
            }
            return default(T);
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
 
    public static List<T> ReaderToList<T>(IDataReader dr)
    {
        using (dr)
        {
            List<string> field = new List<string>(dr.FieldCount);
            for (int i = 0; i < dr.FieldCount; i++)
            {
                field.Add(dr.GetName(i).ToLower());
            }
            List<T> list = new List<T>();
            while (dr.Read())
            {
                T model = Activator.CreateInstance<T>();
                foreach (PropertyInfo property in model.GetType().GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
                {
                    if (field.Contains(property.Name.ToLower()))
                    {
                        if (!IsNullOrDBNull(dr[property.Name]))
                        {
                            property.SetValue(model, HackType(dr[property.Name], property.PropertyType), null);
                        }
                    }
                }
                list.Add(model);
            }
            return list;
        }
    }
 
    //这个类对可空类型进行判断转换,要不然会报错
    private static object HackType(object value, Type conversionType)
    {
        if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value == null)
                return null;
 
            System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(conversionType);
            conversionType = nullableConverter.UnderlyingType;
        }
        return Convert.ChangeType(value, conversionType);
    }
 
    private static bool IsNullOrDBNull(object obj)
    {
        return ((obj is DBNull) || string.IsNullOrEmpty(obj.ToString())) ? true : false;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值