C# ADO.NET根据实体对象类型转换创建DataTable对象
作者:C/S框架网  发布日期:2018-12-10 17:31:43
  C# ADO.NET根据实体对象类型转换创建DataTable对象



C# Code:

/// <summary>
/// 根据类型创建表结构
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static DataTable CreateTable(Type t)
{
   return BuiltTable(t.GetProperties());
}

/// <summary>
/// 根据对象的属性创建数据表
/// </summary>
private static DataTable BuiltTable(PropertyInfo[] pinfo)
{
   try
   {
      if (pinfo == null) return null;
      DataTable table = new DataTable();
      foreach (PropertyInfo info in pinfo)
      {
         Type type = info.PropertyType;
         if (info.PropertyType.IsGenericType)
         type = info.PropertyType.GetGenericArguments()[0];
         DataColumn column = new DataColumn(info.Name, type);
         column.AllowDBNull = true;
         table.Columns.Add(column);
      }
      return table;
   }
   catch { return null; }
}

//来源:C/S框架网(www.csframework.com) QQ:23404761




上一篇 下一篇