using Microsoft.EntityFrameworkCore; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data; using System.Data.Common; using System.IO; using System.Linq; using System.Reflection; using Znyc.Recruitment.Admin.Commons.Extensions; using Znyc.Recruitment.Admin.Commons.IDbContext; namespace Znyc.Recruitment.Admin.Commons.DbContextCore { /// /// public class MySqlDbContext : BaseDbContext, IMySqlDbContext { /// /// 批量插入 /// /// /// 数据实体集合 /// 数据库表名称 public override void BulkInsert(IList entities, string destinationTableName = null) { if (entities == null || !entities.Any()) { return; } if (string.IsNullOrEmpty(destinationTableName)) { string mappingTableName = typeof(T).GetCustomAttribute()?.Name; destinationTableName = string.IsNullOrEmpty(mappingTableName) ? typeof(T).Name : mappingTableName; } MySqlBulkInsert(entities, destinationTableName); } public override DataTable GetDataTable(string sql, int cmdTimeout = 30, params DbParameter[] parameters) { return GetDataTables(sql, cmdTimeout, parameters).FirstOrDefault(); } public override List GetDataTables(string sql, int cmdTimeout = 30, params DbParameter[] parameters) { List dts = new List(); //TODO: connection 不能dispose 或者 用using,否则下次获取connection会报错提示“the connectionstring property has not been initialized。” DbConnection connection = Database.GetDbConnection(); if (connection.State != ConnectionState.Open) { connection.Open(); } using (MySqlCommand cmd = new MySqlCommand(sql, (MySqlConnection)connection)) { cmd.CommandTimeout = cmdTimeout; if (parameters != null && parameters.Length > 0) { cmd.Parameters.AddRange(parameters); } using (MySqlDataAdapter da = new MySqlDataAdapter(cmd)) { using (DataSet ds = new DataSet()) { da.Fill(ds); foreach (DataTable table in ds.Tables) { dts.Add(table); } } } } connection.Close(); return dts; } /// /// /// /// /// private void MySqlBulkInsert(IList entities, string destinationTableName) where T : class { string tmpDir = Path.Combine(AppContext.BaseDirectory, "Temp"); if (!Directory.Exists(tmpDir)) { Directory.CreateDirectory(tmpDir); } string csvFileName = Path.Combine(tmpDir, $"{DateTime.Now:yyyyMMddHHmmssfff}.csv"); if (!File.Exists(csvFileName)) { File.Create(csvFileName); } string separator = ","; entities.SaveToCsv(csvFileName, separator); MySqlConnection conn = (MySqlConnection)Database.GetDbConnection(); if (conn.State != ConnectionState.Open) { conn.Open(); } MySqlBulkLoader bulk = new MySqlBulkLoader(conn) { NumberOfLinesToSkip = 0, TableName = destinationTableName, FieldTerminator = separator, FieldQuotationCharacter = '"', EscapeCharacter = '"', LineTerminator = "\r\n" }; bulk.LoadAsync(); conn.Close(); File.Delete(csvFileName); } } }