DataTable에서 List로 변환<br>일반 클래스

코드:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;

namespace NCL.Data
{
    /// <summary>
    ///        
    /// </summary>
    public class ModelConvertHelper<T> where  T : new()
    {
        public static IList<T> ConvertToModel(DataTable dt)
        {
            //     
            IList<T> ts = new List<T>();

            //         
            Type type = typeof(T);

            string tempName = "";

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();

                //           
                PropertyInfo[] propertys = t.GetType().GetProperties();

                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;

                    //   DataTable      
                    if (dt.Columns.Contains(tempName))
                    {
                        //         Setter
                        if (!pi.CanWrite) continue;

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }

                ts.Add(t);
            }

            return ts;

        }
    }
}

사용 방법:
//조회 결과 가져오기 DataTable dt = DbHelper.ExecuteDataTable(...);//DataTable를 IList IList users = ModelConvertHelper로 변환합니다.ConvertToModel(dt);

좋은 웹페이지 즐겨찾기