public static IList <T> ConvertToList< T>(DataTable dt) where T : new() { List<T > list = new List< T>(); T model = default (T); foreach (DataRow dr in dt.Rows) { model = Activator.CreateInstance<T >(); PropertyInfo[] propertys = model.GetType().GetProperties(); foreach (PropertyInfo pi in propertys) { if (dt.Columns.Contains(pi.Name)) { if (!pi.CanWrite) continue ; object value = dr[pi.Name]; if (value != DBNull .Value) { pi.SetValue(model, value, null); } else { pi.SetValue(model, null, null ); } } } list.Add(model); } return list; } public static DataTable ToDataTable< T>(IEnumerable <T> list) { List<PropertyInfo > pList = new List< PropertyInfo>(); Type type = typeof (T); DataTable dt = new DataTable(); Array.ForEach<PropertyInfo >(type.GetProperties(), p => { pList.Add(p); Type colType = p.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof( Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dt.Columns.Add(p.Name, colType); }); foreach (var item in list) { DataRow row = dt.NewRow(); pList.ForEach(p => row[p.Name] = p.GetValue(item, null) == null ? DBNull.Value : p.GetValue(item, null)); dt.Rows.Add(row); } return dt; }
/// <summary> /// C#系统类型转换为SQL数据库类型 /// </summary> /// <param name=" theType"></param> /// <returns></returns> public static SqlDbType GetDBType(System. Type theType) { System.Data.SqlClient. SqlParameter p1; System.ComponentModel. TypeConverter tc; p1 = new System.Data.SqlClient.SqlParameter (); tc = System.ComponentModel. TypeDescriptor.GetConverter(p1.DbType); if (tc.CanConvertFrom(theType)) { p1.DbType = ( DbType)tc.ConvertFrom(theType.Name); } else { //Try brute force try { p1.DbType = ( DbType)tc.ConvertFrom(theType.Name); } catch (Exception ) { //Do Nothing; will return NVarChar as default } } return p1.SqlDbType; }