private void DoWorkButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var service = new ClassToDataTableService <Person>();

                Random rand           = new Random(DateTime.Now.Second);
                int    numberToCreate = rand.Next(10, 100);

                for (int i = 0; i < numberToCreate; i++)
                {
                    var newPerson = new Person()
                    {
                        FirstName         = $"First{rand.Next(1, 5000)}",
                        LastName          = $"Last{rand.Next(1, 5000)}",
                        Age               = rand.Next(5, 80),
                        PercentageBodyFat = rand.Next(1, 20) / 1.2m,
                        AvgHeartRate      = rand.Next(60, 80) / 1.1
                    };

                    service.AddRow(newPerson);
                }

                LogMessage($"There are {service.Table.Rows.Count} rows in the table now");

                // TODO: Do something with the table:  service.Table
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }
예제 #2
0
        /// <summary>This examples shows how to use the ClassToDataTable service and SQLBulkCopy together.</summary>
        private static async Task SqlCopyWithoutHelperAsync(SqlConnection sqlConnection, string tableSchema,
                                                            string tableName, int batchSize, int bulkCopyTimeoutInSeconds, List <Person> people)
        {
            var classToDataTableService = new ClassToDataTableService <Person>();

            var myBulkCopy = new SqlBulkCopy(sqlConnection)
            {
                DestinationTableName = $"{tableSchema}.{tableName}",
                BatchSize            = batchSize,
                BulkCopyTimeout      = bulkCopyTimeoutInSeconds
            };

            // Column mappings for SQLBulkCopy
            foreach (DataColumn column in classToDataTableService.Table.Columns)
            {
                myBulkCopy.ColumnMappings.Add(column.ColumnName, column.ColumnName);
            }

            foreach (var item in people)
            {
                classToDataTableService.AddRow(item);

                if (classToDataTableService.Count % myBulkCopy.BatchSize == 0)
                {
                    // WRITE to SERVER!
                    await myBulkCopy.WriteToServerAsync(classToDataTableService.Table);

                    classToDataTableService.Clear();
                }
            }

            // Flush any remaining items.
            if (classToDataTableService.Count > 0)
            {
                // WRITE to SERVER!
                await myBulkCopy.WriteToServerAsync(classToDataTableService.Table);
            }
        }