DbBulkExtend.BulkInsert<userVM>(addUserList, table, "SYS_USER"); /// <summary> /// 批量插入 /// </summary> /// <typeparam name="T">泛型集合的类型</typeparam> /// <param name="list">要插入大泛型集合</param> /// <param name="table">内存dt</param> /// <param name="tableName">对应数据库的表名</param> public static void BulkInsert<T>(IList<T> list, DataTable table, string tableName) { var connStr = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
using (var bulkCopy = new SqlBulkCopy(conn)) { conn.Open(); bulkCopy.BatchSize = list.Count; bulkCopy.DestinationTableName = tableName;
var props = TypeDescriptor.GetProperties(typeof(T)) .Cast<PropertyDescriptor>() .ToArray(); var values = new object[props.Length]; foreach (var item in list) { for (var i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } bulkCopy.WriteToServer(table); conn.Close(); } }
/// <summary> /// 构建内存dt列 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <returns></returns> public static DataTable GetModelProperty<T>(T model) { DataTable table = new DataTable(); //取得m的Type实例 Type t = model.GetType(); //取得类的属性名并获取属性值 foreach (System.Reflection.PropertyInfo s in t.GetProperties()) //循环遍历 { Type pType = s.PropertyType; table.Columns.Add(s.Name, pType); } return table; }
/// <summary> /// 获取表名 /// </summary> /// <param name="typeInfo"></param> /// <returns></returns> public static string GetTableName(Type typeInfo) { var os = typeInfo.GetCustomAttributes(false); var displayName = ((TableAttribute[])typeInfo.GetCustomAttributes(typeof(TableAttribute), false)).FirstOrDefault(); if (displayName != null && displayName.Name.Length > 0) { return displayName.Name; } else { return ""; } }