1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- using Bowin.Common.Data;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- 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;
- namespace YLShipBuildLandMap.Entity.Extensions
- {
- public static class DbSetExpression
- {
- public static void BulkInsertsBySqlBulkCopy<T>(this DbSet<T> @this, List<T> list) where T : class, new()
- {
- var dbContext = YLShipBuildLandMapContext.Services.GetService<YLShipBuildLandMapContext>();
- var sqlConn = (SqlConnection)dbContext.Database.GetDbConnection();
- if (sqlConn.State == ConnectionState.Closed)
- {
- sqlConn.Open();
- }
- using (SqlBulkCopy sbc = new SqlBulkCopy(sqlConn))
- {
- //sbc.BulkCopyTimeout = 60;//超时时间
- Type type = typeof(T);
- var mapping = dbContext.Model.FindEntityType(typeof(T));
- //设置要插入的表名
- sbc.DestinationTableName = mapping.GetTableName();
- T s = new T();
- PropertyInfo[] ps = s.GetType().GetProperties();
- List<string> columnList = new List<string>();
- foreach (PropertyInfo pi in ps.Where(w => !w.GetGetMethod().IsVirtual && w.Name != "Feilds"))
- {
- var column = dbContext.Model.FindEntityType(typeof(T)).FindProperty(pi);
- sbc.ColumnMappings.Add(pi.Name, column.GetColumnName());//与服务器数据库列名映射,
- columnList.Add(pi.Name);
- }
- DataTable dt = list.ToTable(columnList);
- //执行
- sbc.WriteToServer(dt);
- }
- }
- }
- }
|