using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Common
{
public class BulkInsert
{
private string connectionString;
public BulkInsert(string _con)
{
cOnnectionString= ConfigurationManager.ConnectionStrings[_con].ConnectionString;
}
public BulkInsert(string _con, bool DESE)
{
cOnnectionString= DESEncrypt.Decrypt(ConfigurationManager.ConnectionStrings[_con].ConnectionString);
}
public void WriteToServer(List list, string TableName)
{
using (SqlConnection destinatiOnConnection= new SqlConnection(connectionString))
{
DataTable dt = list.ToDataTable();
destinationConnection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinatiOnTableName= TableName;
bulkCopy.NotifyAfter = 30000;
try
{
bulkCopy.WriteToServer(dt);
Console.WriteLine("{0}插入{1}条数据", TableName, list.Count);
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
throw ex;
}
finally
{
}
}
}
}
}
public static class DataTableHelper
{
public static DataTable ToDataTable(this List list)
{
//创建属性的集合
List pList = new List();
//获得反射的入口
Type type = typeof(T);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in list)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
}
public static IEnumerable Distinct(this IEnumerable source, Func keySelector)
{
return source.Distinct(new CommonEqualityComparer(keySelector));
}
}
public class CommonEqualityComparer : IEqualityComparer
{
private Func keySelector;
public CommonEqualityComparer(Func keySelector)
{
this.keySelector = keySelector;
}
public bool Equals(T x, T y)
{
return EqualityComparer.Default.Equals(keySelector(x), keySelector(y));
}
public int GetHashCode(T obj)
{
return EqualityComparer.Default.GetHashCode(keySelector(obj));
}
}
}
SqlBulkCopy 帮助类