DbSetExpression.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using Bowin.Common.Data;
  2. using Microsoft.EntityFrameworkCore;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.DependencyInjection;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.Data.SqlClient;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Text;
  13. namespace YLShipBuildLandMap.Entity.Extensions
  14. {
  15. public static class DbSetExpression
  16. {
  17. public static void BulkInsertsBySqlBulkCopy<T>(this DbSet<T> @this, List<T> list) where T : class, new()
  18. {
  19. var dbContext = YLShipBuildLandMapContext.Services.GetService<YLShipBuildLandMapContext>();
  20. var sqlConn = (SqlConnection)dbContext.Database.GetDbConnection();
  21. if (sqlConn.State == ConnectionState.Closed)
  22. {
  23. sqlConn.Open();
  24. }
  25. using (SqlBulkCopy sbc = new SqlBulkCopy(sqlConn))
  26. {
  27. //sbc.BulkCopyTimeout = 60;//超时时间
  28. Type type = typeof(T);
  29. var mapping = dbContext.Model.FindEntityType(typeof(T));
  30. //设置要插入的表名
  31. sbc.DestinationTableName = mapping.GetTableName();
  32. T s = new T();
  33. PropertyInfo[] ps = s.GetType().GetProperties();
  34. List<string> columnList = new List<string>();
  35. foreach (PropertyInfo pi in ps.Where(w => !w.GetGetMethod().IsVirtual && w.Name != "Feilds"))
  36. {
  37. var column = dbContext.Model.FindEntityType(typeof(T)).FindProperty(pi);
  38. sbc.ColumnMappings.Add(pi.Name, column.GetColumnName());//与服务器数据库列名映射,
  39. columnList.Add(pi.Name);
  40. }
  41. DataTable dt = list.ToTable(columnList);
  42. //执行
  43. sbc.WriteToServer(dt);
  44. }
  45. }
  46. }
  47. }