將DataRow轉成指定類型的類,並返回這個類的對象(帶值)

摘要:將DataRow轉成指定類型的類,並返回這個類的對象(帶值)

private Object ConvertToEntity(DataRow pDataRow, Type pType)
        {
            Object entity = null;
            Object proValue = null;
            PropertyInfo propertyInfo = null;
            try
            {
                if (pDataRow != null)
                {
                    //動態創建類的實例
                    entity = Activator.CreateInstance(pType);
                    foreach (DataColumn dc in pDataRow.Table.Columns)
                    {
                        //忽略綁定時的大小寫
                        propertyInfo = pType.GetProperty(dc.ColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        proValue = pDataRow[dc];
                        //當值不為空時
                        if (proValue != DBNull.Value)
                        {
                            try
                            {   
                                propertyInfo.SetValue(entity, Convert.ChangeType(proValue, dc.DataType), null);
                            }
                            catch 
                            {
                                continue;
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                entity = null;
            }
            return entity;
        } 


人生到處知何似
應似飛鴻踏雪泥