无情小侠

Everyday type conversion-ClassHelper

一、DataTable与实体类互相转换   

/// <summary>
///功能说明:根据实体类得到表结构,
/// 创建人:卜发相
/// 创建日期:2012-4-20
/// </summary>
/// <param name="model">实体</param>
/// <param name="status">操作状态,add添加主键字段,upload不添加主键字段</param>
/// <returns></returns>    
public DataTable ModelToDataTable(T model, string status)    
{        
     DataTable dataTable = new DataTable(typeof(T).Name);      
     foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())      
     {        
        switch (status)        
        {           
          case "add":           
          if (!propertyInfo.IsDefined(typeof(CloudCall.MODEL.PKAttribute), false))//此处红色标识为实体中是否加有主键特性          
          {             
               dataTable.Columns.Add(new DataColumn(propertyInfo.Name, GetDataType(propertyInfo)));          
          }          
          break;          
          case "upload":          
          dataTable.Columns.Add(new DataColumn(propertyInfo.Name, GetDataType(propertyInfo)));          
          break;         
          default:         
          break;        
       }      
  }    
     return dataTable;
}
/// <summary>
/// 功能说明:根据DataRow填充对象:用DataRow填充实体类
/// 创建人:卜发相
/// 创建日期:2012-5-10
/// </summary>
/// <param name="table">table</param>
/// <returns>T</returns>       
public T DataTableToT(DataTable table)        
{            
   if (table.Rows.Count == 0)            
   {
      return default(T);            
   }           
   else            
   {                
     T model = new T();                
     foreach (DataRow row in table.Rows)                
     {                    
      foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())                   
      {                        
      model.GetType().GetProperty(propertyInfo.Name).SetValue(model, GteDataTypes(propertyInfo, row[propertyInfo.Name].ToString()), null);                    
      }               
  }                
    return model;      
   }     
 }

二、Databale于List<T>相互转换

public static class ConvertHelper<T> where T : new()    

{

/// <summary>          

/// 利用反射和泛型          

/// </summary>          

/// <param name="dt"></param>          

/// <returns></returns>          

public static List<T> ConvertToList(DataTable dt)        

{              

  List<T> ts = new List<T>();// 定义集合

  Type type = typeof(T);// 获得此模型的类型

  string tempName = string.Empty;//定义一个临时变量                          

  foreach (DataRow dr in dt.Rows) //遍历DataTable中所有的数据行            

  {                

      T t = new T();  // 获得此模型的公共属性                  

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

      foreach (PropertyInfo pi in propertys)//遍历该对象的所有属性                  

      {                    

         tempName = pi.Name;//将属性名称赋值给临时变量  

         if (dt.Columns.Contains(tempName))//检查DataTable是否包含此列(列名==对象的属性名)

         {                        

           // 判断此属性是否有Setter                          

           if (!pi.CanWrite) continue;//该属性不可写,直接跳出                          

          //取值object value = dr[tempName];                                         

          if (value != DBNull.Value)      //如果非空,则赋给对象的属性                         

          pi.SetValue(t, TypeConversion.GetDataType(pi, value.ToString()), null);                    

          }

       }                  

    ts.Add(t);      //对象添加到泛型集合中       

   }

   return ts;

 }    

}

/// <summary>            

/// 功能说明: 将一个列表转换成DataTable,如果列表为空将返回空的DataTable结构            

/// 创建人:卜发相            

/// 创建日期:2012-4-22           

  ///  </summary>            

/// <typeparam name="T">要转换的数据类型</typeparam>            

/// <param name="entityList">实体对象列表</param>            

public static DataTable EntityListToDataTable<T>(List<T> entityList)            

{                

DataTable dt = new DataTable();

                //取类型T所有Propertie                

Type entityType = typeof(T);                

PropertyInfo[] entityProperties = entityType.GetProperties();                

Type colType = null;               

  foreach (PropertyInfo propInfo in entityProperties)                

{

                    if (propInfo.PropertyType.IsGenericType)                   

  {                       

colType = Nullable.GetUnderlyingType(propInfo.PropertyType);                   

  }                    

else                    

{                        

colType = propInfo.PropertyType;                    

}

                    if (colType.FullName.StartsWith("System"))                   

  {                     

    if (!propInfo.IsDefined(typeof(CloudCall.MODEL.PKAttribute), false))            

             {                     

        dt.Columns.Add(propInfo.Name, colType);                     

    }              

       }             

    }

                if (entityList != null && entityList.Count > 0)           

      {                 

    foreach (T entity in entityList)          

           {                     

    DataRow newRow = dt.NewRow();             

            foreach (PropertyInfo propInfo in entityProperties)         

                {                     

        if (dt.Columns.Contains(propInfo.Name))             

                {                             

    object objValue = propInfo.GetValue(entity, null);                         

        newRow[propInfo.Name] = objValue == null ? DBNull.Value : objValue;                             }                         }                         dt.Rows.Add(newRow);                  

   }              

   }

                return dt;        

     }

三、DataSet于JSON互相转换

public class DataJson     {

/// <summary>   

/// 将JSON转化成DataSet数据     

/// </summary>            

/// <param name="ds"></param>            

/// <returns></returns>        

public static DataSet JsonToDataSet(string Json)        

{            

try            

{                

DataSet ds = new DataSet();                 J

avaScriptSerializer JSS = new JavaScriptSerializer();

object obj = JSS.DeserializeObject(Json);                

Dictionary<string, object> datajson = (Dictionary<string, object>)obj;

  foreach (var item in datajson)                

{                    

DataTable dt = new DataTable(item.Key);                    

object[] rows = (object[])item.Value;                    

foreach (var row in rows)                    

{                       

  Dictionary<string, object> val = (Dictionary<string, object>)row;                        

DataRow dr = dt.NewRow();                        

foreach (KeyValuePair<string, object> sss in val)                        

{                           

  if (!dt.Columns.Contains(sss.Key))                           

  {                               

  dt.Columns.Add(sss.Key.ToString());                                

dr[sss.Key] = sss.Value;                            

}                           

  else                                

dr[sss.Key] = sss.Value;                      

   }                        

dt.Rows.Add(dr);                 

    }                   

  ds.Tables.Add(dt);                

}                

return ds;           

  }            

catch         

    {             

    return null;     

        }       

  }

/// <summary>        

/// 将DataSet转化成JSON数据        

/// </summary>        

/// <param name="ds"></param>        

/// <returns></returns>        

public static string DataSetToJson(DataSet ds)        

{            

string json = string.Empty;          

   try        

     {          

       if (ds.Tables.Count == 0)             

        throw new Exception("DataSet中Tables为0");   

              json = "{";                

for (int i = 0; i < ds.Tables.Count; i++)            

     {                 

    json += "T" + (i + 1) + ":[";              

       for (int j = 0; j < ds.Tables[i].Rows.Count; j++)      

               {                   

      json += "{";                    

     for (int k = 0; k < ds.Tables[i].Columns.Count; k++)       

                  {                         

    json += ds.Tables[i].Columns[k].ColumnName + ":'" + ds.Tables[i].Rows[j][k].ToString() + "'";                            

if (k != ds.Tables[i].Columns.Count - 1)                                

json += ",";                     

    }                        

json += "}";                        

if (j != ds.Tables[i].Rows.Count - 1)                            

json += ",";                    

}                  

   json += "]";                    

if (i != ds.Tables.Count - 1)                        

json += ",";

                }                

json += "}";            

}            

catch (Exception ex)            

{                

throw new Exception(ex.Message);       

      }            

return json;     

    }    

}

}

四、以上转换中的值类型转换(Table于List<T>互相转换必须引用)

#region 类型转换        

#region 转换当前遍历到的数据类型填充到对应对象 + public object GteDataTypes(PropertyInfo property, string value)        

/// <summary>        

/// 功能说明:转换当前遍历到的数据类型填充到对应对象;        

/// 创建人:卜发相        

/// 创建日期:2012-5-10        

/// </summary>        

/// <param name="property"></param>        

/// <param name="value">值</param>        

/// <returns></returns>        

public object GteDataTypes(PropertyInfo property, string value)        

{            

string proName = property.PropertyType.FullName;            

if (value == "")           

  {                

return null;            

}          

   else       

      {            

     if (proName.Contains("Int32"))  

               {          

           return Convert.ToInt32(value);           

      }               

  else if (proName.Contains("String"))           

      {                    

return Convert.ToString(value);            

     }               

  else if (proName.Contains("DateTime"))            

     {                   

  return Convert.ToDateTime(value);           

      }            

     else if (proName.Contains("Boolean"))            

     {                    

return Convert.ToBoolean(value);           

      }

  else if (proName.Contains("System.Guid"))          

       {                   

  return new System.Guid(value);          

       }               

  else           

      {              

       return null;   

              }        

     }        

}        

#endregion

#region 获取当前属性元数据的类型+private Type GetDataType(PropertyInfo property)        

/// <summary>        

/// 功能说明:获取当前属性元数据的类型;        

/// 创建人:袁源        

/// 创建日期:2012-4-20        

/// </summary>        

/// <param name="property"></param>        

/// <returns>Type</returns>        

public Type GetDataType(PropertyInfo property)        

{            

string proName = property.PropertyType.FullName;            

if (proName.Contains("Int32"))            

{               

  return typeof(int);           

  }          

   else if (proName.Contains("String"))       

      {                

return typeof(string);     

        }          

   else if (proName.Contains("DateTime"))   

          {              

   return typeof(DateTime);     

        }       

      else if (proName.Contains("Boolean"))

            {             

    return typeof(bool);          

   }          

   else if (proName.Contains("System.Guid"))       

      {               

  return typeof(System.Guid);       

      }          

   else          

   {     

            return null;       

      }  

       }      

   #endregion     

    #endregion    

}

posted @ 2012-05-12 08:12  码农界的卧底  阅读(785)  评论(0编辑  收藏  举报