DatableからList/DataRowへエンティティークラスオブジェクトへ


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace cfzs.DAL
{
    public class BaseDAL
    {
        #region DataTale      
        /// 
        /// DataTale      
        /// 
        ///      
        /// DataTable
        /// List
        public List DataTableToModelList(DataTable table)
        {
            List list = new List();
            T t = default(T);
            PropertyInfo[] propertypes = null;
            string tempName = string.Empty;
            foreach (DataRow row in table.Rows)
            {
                t = Activator.CreateInstance();
                propertypes = t.GetType().GetProperties();
                foreach (PropertyInfo pro in propertypes)
                {
                    tempName = pro.Name;
                    if (table.Columns.Contains(tempName))
                    {
                        object value = row[tempName];
                        if (value.GetType() == typeof(System.DBNull))
                        {
                            value = null;
                        }
                        pro.SetValue(t, value, null);
                    }
                }
                list.Add(t);
            }
            return list;
        }
        #endregion
        #region   DataRow     
        /// 
        /// DataRow     
        /// 
        ///      
        /// DataRow
        /// T
        public T DataRowToModel(DataRow row)
        {

            T t = default(T);
            PropertyInfo[] propertypes = null;
            string tempName = string.Empty;
            t = Activator.CreateInstance();
            propertypes = t.GetType().GetProperties();
            foreach (PropertyInfo pro in propertypes)
            {
                tempName = pro.Name;
                if (row.Table.Columns.Contains(tempName))
                {
                    object value = row[tempName];
                    if (value.GetType() == typeof(System.DBNull))
                    {
                        value = null;
                    }
                    pro.SetValue(t, value, null);
                }
            }
            return t;
        }
        #endregion
    }
}