net6 批量存 表
WagesTaxationDtonew
#region 存表
{
using (TransactionScope transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
if (Conn.State != ConnectionState.Open) Conn.Open();
DataTable dtHeader = copyToDataTable(Conn, WagesTaxationDtonew.ToList(), "WageOutputPiece");
SqlTransaction tran = (SqlTransaction)Conn.BeginTransaction();
try
{
await WriteToServer(Conn, dtHeader, "WageOutputPiece", tran);
await tran.CommitAsync();
}
catch (Exception e)
{
await tran.RollbackAsync();
throw new Exception(e.Message);
}
finally
{
if (Conn.State == ConnectionState.Open) Conn.Close();
}
transactionScope.Complete();
}
}
#endregion
#region common
private DataTable copyToDataTable<T>(IDbConnection conn, IList<T> list, string tableName) where T : class
{
Type objType = typeof(T);
var modelPropList = typeof(T).GetProperties().Where(x => x.CustomAttributes.All(y => y.AttributeType != typeof(NotMappedAttribute)));
DataTable dt = getTableScheme(conn, tableName);
dt.TableName = tableName;
foreach (T model in list)
{
DataRow dataRow = dt.NewRow();
foreach (PropertyInfo propertyInfo in modelPropList)
{
ComExtend.setRowValue(dataRow, propertyInfo.Name, propertyInfo.GetValue(model));
//dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
}
dt.Rows.Add(dataRow);
}
return dt;
}
private async Task WriteToServer(IDbConnection conn, DataTable dt, string tableName, SqlTransaction tran)
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy((SqlConnection)conn, SqlBulkCopyOptions.KeepNulls | SqlBulkCopyOptions.FireTriggers, tran))//批量保存
{
sqlBulkCopy.DestinationTableName = tableName;
dt.TableName = tableName;
sqlBulkCopy.BatchSize = dt.Rows.Count;
await sqlBulkCopy.WriteToServerAsync(dt);
}
}
private DataTable getTableScheme(IDbConnection conn, string tableName)
{
var cmd1 = (SqlCommand)conn.CreateCommand();
cmd1.CommandText = "select top 0 * from " + tableName;
SqlDataAdapter adapter1 = new SqlDataAdapter(cmd1);
DataTable dt = new DataTable();
adapter1.Fill(dt);
return dt;
}
#endregion