DataReader,DataTable利用泛型填充实体类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///TestTableModel 的摘要说明
/// </summary>
public class TestTableModel
{
    public int D_Id { get; set; }
    public string D_Name { get; set; }
    public string D_Password { get; set; }
    public string D_Else { get; set; }
    public decimal D_Amount { get; set; }
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;

namespace MSCL
{
    /// <summary>
    ///ObjectToList 的摘要说明
    /// </summary>
    public static class ObjectToList
    {
        /*  --示例
            IDataReader dr = MSCL.SqlHelper.GetSqlDataReader("select * from TestTable where d_id in(6,7,8)");
            List<TestTableModel> t1 = MSCL.ObjectToList.DataReaderToList<TestTableModel>(dr);
            for (int i = 0; i < t1.Count; i++)
            {
                Response.Write(t1[i].D_Id + "<br/>");
                Response.Write(t1[i].D_Name + "<br/>");
                Response.Write(t1[i].D_Password + "<br/>");
                Response.Write(t1[i].D_Else + "<br/>");
                Response.Write(t1[i].D_Amount + "<br/>");
            }   
            dr.Dispose();
            dr.Close();
         */

        /// <summary>
        /// DataReader利用泛型填充实体类
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="reader">DataReader</param>
        /// <returns></returns>
        public static List<T> DataReaderToList<T>(IDataReader reader)
        {
            //实例化一个List<>泛型集合
            List<T> DataList = new List<T>();
            while (reader.Read())
            {
                T RowInstance = Activator.CreateInstance<T>();//动态创建数据实体对象
                //通过反射取得对象所有的Property
                foreach (PropertyInfo Property in typeof(T).GetProperties())
                {
                    try
                    {
                        //取得当前数据库字段的顺序
                        int Ordinal = reader.GetOrdinal(Property.Name);
                        if (reader.GetValue(Ordinal) != DBNull.Value)
                        {
                            //将DataReader读取出来的数据填充到对象实体的属性里
                            Property.SetValue(RowInstance, Convert.ChangeType(reader.GetValue(Ordinal), Property.PropertyType), null);
                        }
                    }
                    catch
                    {
                        break;
                    }
                }
                DataList.Add(RowInstance);
            }
            return DataList;
        }

        /// <summary>
        /// DataTable利用泛型填充实体类
        /// </summary>
        /// <typeparam name="T">实体类</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<T> DataTableToList<T>(DataTable dt) where T : new()
        {
            var list = new List<T>();
            if (dt == null) return list;
            var len = dt.Rows.Count;

            for (var i = 0; i < len; i++)
            {
                var info = new T();
                foreach (DataColumn dc in dt.Rows[i].Table.Columns)
                {
                    var field = dc.ColumnName;
                    var value = dt.Rows[i][field].ToString();
                    if (string.IsNullOrEmpty(value)) continue;
                    if (IsDate(value))
                    {
                        value = DateTime.Parse(value).ToString();
                    }

                    var p = info.GetType().GetProperty(field);

                    try
                    {
                        if (p.PropertyType == typeof(string))
                        {
                            p.SetValue(info, value, null);
                        }
                        else if (p.PropertyType == typeof(int))
                        {
                            p.SetValue(info, int.Parse(value), null);
                        }
                        else if (p.PropertyType == typeof(bool))
                        {
                            p.SetValue(info, bool.Parse(value), null);
                        }
                        else if (p.PropertyType == typeof(DateTime))
                        {
                            p.SetValue(info, DateTime.Parse(value), null);
                        }
                        else if (p.PropertyType == typeof(float))
                        {
                            p.SetValue(info, float.Parse(value), null);
                        }
                        else if (p.PropertyType == typeof(double))
                        {
                            p.SetValue(info, double.Parse(value), null);
                        }
                        else
                        {
                            p.SetValue(info, value, null);
                        }
                    }
                    catch (Exception)
                    {
                        //p.SetValue(info, ex.Message, null); 
                    }
                }
                list.Add(info);
            }
            dt.Dispose(); dt = null;
            return list;
        }

        /// <summary>
        /// 是否是时间
        /// </summary>
        /// <param name="d"></param>
        /// <returns></returns>
        private static bool IsDate(string d)
        {
            DateTime d1;
            double d2;
            return !double.TryParse(d, out d2) && DateTime.TryParse(d, out d1);
        }
    }
}

转载于:https://www.cnblogs.com/smartsmile/p/6234256.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值