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(this DbSet @this, List list) where T : class, new() { var dbContext = YLShipBuildLandMapContext.Services.GetService(); 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 columnList = new List(); 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); } } } }