Class BaseSqlWriter
- Namespace
- Dynamicweb.DataIntegration.Integration
- Assembly
- Dynamicweb.DataIntegration.dll
Base class for destination writers that write to a Microsoft SQL Server database using the temporary-table
import pattern: the writer bulk-copies the converted source rows into a temporary table named
{DestinationTableName}{tempTablePrefix}, and the static helpers on this class then merge the temporary
table into the main table and delete or deactivate rows that were missing from the source. Destination providers
create their writer in RunJob(Job); the built-in
SqlDestinationWriter, EcomDestinationWriter, OrderDestinationWriter,
UserDestinationWriter and DynamicwebBulkInsertDestinationWriter all derive from this class.
public abstract class BaseSqlWriter : BaseDestinationWriter, IDestinationWriter
- Inheritance
-
BaseSqlWriter
- Implements
- Derived
- Inherited Members
Remarks
How to create a custom SQL writer: Subclass this class and implement IDestinationWriter:
create the temporary table up front, buffer rows in a DataTable from Write and flush them
with SqlBulkCopy (optionally through
SqlBulkCopierWriteToServer(SqlBulkCopy, DataTable, bool, Mapping, ILogger?)), and when all rows are
written call MoveDataToMainTable(SqlCommand, Mapping, SqlTransaction, string) inside a transaction,
followed by DeleteExcessFromMainTable(SqlCommand, Mapping, string, string, bool) when "remove
missing rows after import" is enabled. See Dynamicweb.DataIntegration.Providers.SqlProvider.SqlDestinationWriter
for the reference implementation.
Things to be careful of:
- This class inherits BaseDestinationWriter, whose members all throw
NotImplementedException and are non-virtual. A derived writer must hide the members it implements
with
newand re-declare IDestinationWriter on the class (asSqlDestinationWriter : BaseSqlWriter, IDestinationWriterdoes); otherwise calls made through the interface dispatch to the throwing base implementations. - The helpers compose SQL from mapping metadata — schema, table and column names are
bracket-quoted into the statement text — so they are intended for trusted mapping configuration only, and they
expect the temporary table to follow the
{DestinationTableName}{tempTablePrefix}naming convention (DeactivateMissingProductsInMainTable(Mapping, SqlCommand, string, string, bool) expectsTempTableForBulkImport{mapping id}). - The helpers execute the supplied SqlCommand directly by replacing its
CommandText; the command's connection must be open (only MoveDataToMainTable(Mapping, SqlCommand, SqlTransaction, string, bool, bool) opens it itself), and the transaction passed toMoveDataToMainTableis assigned to the command. - Updates and deletes are matched on the active column mappings whose destination column is a key column — or on all mapped columns when no key column is defined. Make sure the mapping declares sensible keys before merging.
- Several helpers contain Ecom-schema-specific behavior:
GetExtraConditions(Mapping, string, string) only produces conditions for Ecom tables, and
DeleteExcessFromMainTable(SqlCommand, Mapping, string, string, bool) additionally cleans the
product relation tables when the destination table is
EcomProducts. - Failures are rethrown as InvalidOperationException with the executed SQL text in the message, so the statement can end up in job logs.
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
using Dynamicweb.DataIntegration.Integration;
using Dynamicweb.DataIntegration.Integration.Interfaces;
public class MyDestinationWriter : BaseSqlWriter, IDestinationWriter, IDisposable
{
private const string TempTablePrefix = "TempTableForMyImport";
private readonly SqlCommand _command;
private readonly SqlBulkCopy _bulkCopier;
private readonly DataTable _tableToWrite = new();
public new Mapping Mapping { get; }
public MyDestinationWriter(Mapping mapping, SqlConnection connection)
{
Mapping = mapping;
_command = connection.CreateCommand();
_bulkCopier = new SqlBulkCopy(connection)
{
DestinationTableName = mapping.DestinationTable?.Name + TempTablePrefix
};
// Create the temporary table and add matching columns to _tableToWrite here.
}
public new void Write(Dictionary<string, object> row)
{
// Add the converted row to _tableToWrite; flush in batches.
if (_tableToWrite.Rows.Count >= 1000)
{
SqlBulkCopierWriteToServer(_bulkCopier, _tableToWrite, skipFailingRows: false, Mapping, logger: null);
_tableToWrite.Clear();
}
}
public void FinishWriting(SqlTransaction transaction)
{
SqlBulkCopierWriteToServer(_bulkCopier, _tableToWrite, skipFailingRows: false, Mapping, logger: null);
RowsAffected += MoveDataToMainTable(_command, Mapping, transaction, TempTablePrefix);
}
public new void Close()
{
// Drop the temporary table and dispose _bulkCopier and _command here.
}
public void Dispose() => Close();
}
Properties
RowsAffected
Gets or sets the number of rows the writer has affected in the destination database. Maintained by the derived writer (typically incremented with the results of the merge and delete helpers); destination providers accumulate it into TotalRowsAffected after each mapping.
public virtual int RowsAffected { get; set; }
Property Value
Methods
DeactivateMissingProductsInMainTable(Mapping, SqlCommand, string, string, bool)
Deactivates existing products that are missing from the import source: sets ProductActive = 0 (and
ProductHidden = 1 when requested) on rows in the destination table that have no matching row — by key
columns — in the temporary table named {DestinationTableName}TempTableForBulkImport{mapping id}.
Intended as an alternative to deleting missing products.
protected static int DeactivateMissingProductsInMainTable(Mapping mapping, SqlCommand sqlCommand, string shop, string languageId, bool hideDeactivatedProducts)
Parameters
mappingMappingThe
EcomProductsmapping being imported.sqlCommandSqlCommandThe command used to execute the update; its
CommandTextis replaced and its connection must be open.shopstringThe shop id to restrict the deactivation to; empty for all shops (see GetExtraConditions(Mapping, string, string)).
languageIdstringThe Ecom language id to restrict the deactivation to; empty for all languages.
hideDeactivatedProductsboolWhen
true, also setsProductHidden = 1on the deactivated products.
Returns
- int
The number of deactivated rows.
Exceptions
- InvalidOperationException
Thrown when the update fails; the message includes the executed SQL.
DeactivateMissingProductsInMainTable(Dictionary<string, Mapping>, IEnumerable<Mapping>, SqlCommand, string, string, bool)
Deactivates the products that are not present in any of the import sources, comparing the destination table to several temporary tables at once. The mappings form one combined source dataset, so a product is deactivated only when it is missing from every one of their temporary tables - deactivating per mapping instead would deactivate the products a sibling mapping into the same table just imported.
protected static int DeactivateMissingProductsInMainTable(Dictionary<string, Mapping> mappings, IEnumerable<Mapping> conditionalMappings, SqlCommand sqlCommand, string shop, string languageId, bool hideDeactivatedProducts)
Parameters
mappingsDictionary<string, Mapping>Temporary table prefixes and their mappings; all mappings must share the same destination table.
conditionalMappingsIEnumerable<Mapping>The mappings whose conditionals scope the update; pass an empty set for no conditional restriction.
sqlCommandSqlCommandThe command used to execute the update; its
CommandTextis replaced and its connection must be open.shopstringThe shop the extra conditions restrict the update to; pass an empty string for none.
languageIdstringThe language the extra conditions restrict the update to; pass an empty string for none.
hideDeactivatedProductsboolWhen
true, the deactivated products are hidden as well.
Returns
- int
The number of deactivated rows.
Remarks
conditionalMappings scopes the update the same way it scopes the delete this replaces: only
the part of the destination table the driving mappings cover may be deactivated. Passing an empty set leaves
the update unrestricted, which is what the single-mapping
DeactivateMissingProductsInMainTable(Mapping, SqlCommand, string, string, bool) does.
DeleteExcessFromMainTable(Mapping, string, SqlCommand, string, bool)
Deletes rows not present in the import source. Legacy overload that delegates to DeleteExcessFromMainTable(SqlCommand, Mapping, string, string, bool) and discards the row count.
protected static void DeleteExcessFromMainTable(Mapping mapping, string extraConditions, SqlCommand sqlCommand, string tempTablePrefix, bool removeMissingAfterImportDestinationTablesOnly)
Parameters
mappingMappingThe mapping whose destination table the rows are deleted from.
extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.sqlCommandSqlCommandThe command used to execute the delete; its
CommandTextis replaced and its connection must be open.tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
removeMissingAfterImportDestinationTablesOnlyboolWhen
true, skips the Ecom relation-table cleanup and only deletes from the destination table itself.
DeleteExcessFromMainTable(SqlCommand, Mapping, string, string, bool)
Deletes rows not present in the import source, honoring the mapping's RemoveMissingAfterImport option:
nothing is deleted when the option is explicitly disabled and
removeMissingAfterImportDestinationTablesOnly is false. When the destination table
is EcomProducts (and not restricted to destination tables only), the product relation tables
(EcomProductCategoryFieldValue, EcomVariantOptionsProductRelation, EcomAssortmentItems,
EcomAssortmentProductRelations) are cleaned up first.
protected static long DeleteExcessFromMainTable(SqlCommand sqlCommand, Mapping mapping, string extraConditions, string tempTablePrefix, bool removeMissingAfterImportDestinationTablesOnly)
Parameters
sqlCommandSqlCommandThe command used to execute the deletes; its
CommandTextis replaced and its connection must be open.mappingMappingThe mapping whose destination table the rows are deleted from.
extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
removeMissingAfterImportDestinationTablesOnlyboolWhen
true, skips the Ecom relation-table cleanup and deletes from the destination table even when the mapping option is disabled.
Returns
- long
The total number of deleted rows across the destination and relation tables.
DeleteExcessFromMainTable(SqlCommand, Dictionary<string, Mapping>, IEnumerable<Mapping>, string, bool)
Deletes rows not present in any of the import sources, comparing the shared destination table to several
temporary tables at once, and applies the same guards as the single-mapping
DeleteExcessFromMainTable(SqlCommand, Mapping, string, string, bool): mappings that opted out of
RemoveMissingAfterImport do not drive a delete, nothing is deleted when none of them drives one, and
the EcomProducts relation tables are cleaned up first.
protected static long DeleteExcessFromMainTable(SqlCommand sqlCommand, Dictionary<string, Mapping> mappings, IEnumerable<Mapping> deletingMappings, string extraConditions, bool removeMissingAfterImportDestinationTablesOnly)
Parameters
sqlCommandSqlCommandThe command used to execute the deletes; its
CommandTextis replaced and its connection must be open.mappingsDictionary<string, Mapping>Temporary table prefixes and their mappings, forming the combined source dataset; all mappings must share the same destination table.
deletingMappingsIEnumerable<Mapping>The mappings that may drive the delete, scoping it through their conditionals.
extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.removeMissingAfterImportDestinationTablesOnlyboolWhen
true, skips the Ecom relation-table cleanup and deletes from the destination table even when a mapping option is disabled.
Returns
- long
The total number of deleted rows across the destination and relation tables.
Remarks
A mapping left out of deletingMappings - because it imported no rows, is inactive, or opted
out - must still be listed in mappings: its temporary table is what keeps the rows it
imported from counting as missing from the source and being deleted on another mapping's behalf.
DeleteExcessFromMainTable(SqlCommand, Dictionary<string, Mapping>, string)
Deletes rows not present in any of the import sources, comparing the shared destination table to several
temporary tables at once. Delegates to
DeleteRowsFromMainTable(bool, Dictionary<string, Mapping>, string, SqlCommand) with
deleteExistingRows set to false.
protected static long DeleteExcessFromMainTable(SqlCommand sqlCommand, Dictionary<string, Mapping> mappings, string extraConditions)
Parameters
sqlCommandSqlCommandThe command used to execute the delete; its
CommandTextis replaced and its connection must be open.mappingsDictionary<string, Mapping>Temporary table prefixes and their mappings; all mappings must share the same destination table.
extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.
Returns
- long
The number of deleted rows.
DeleteExistingFromMainTable(Mapping, string, SqlCommand, string)
Deletes existing destination rows that are present in the import source, typically used by "delete incoming rows" import modes. Legacy overload that delegates to DeleteExistingFromMainTable(SqlCommand, Mapping, string, string) and discards the row count.
protected static void DeleteExistingFromMainTable(Mapping mapping, string extraConditions, SqlCommand sqlCommand, string tempTablePrefix)
Parameters
mappingMappingThe mapping whose destination table the rows are deleted from.
extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.sqlCommandSqlCommandThe command used to execute the delete; its
CommandTextis replaced and its connection must be open.tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
DeleteExistingFromMainTable(SqlCommand, Mapping, string, string)
Deletes existing destination rows that are present in the import source, typically used by "delete incoming
rows" import modes. Delegates to
DeleteRowsFromMainTable(bool, Dictionary<string, Mapping>, string, SqlCommand) with
deleteExistingRows set to true.
protected static int DeleteExistingFromMainTable(SqlCommand sqlCommand, Mapping mapping, string extraConditions, string tempTablePrefix)
Parameters
sqlCommandSqlCommandThe command used to execute the delete; its
CommandTextis replaced and its connection must be open.mappingMappingThe mapping whose destination table the rows are deleted from.
extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
Returns
- int
The number of deleted rows.
DeleteRowsFromMainTable(bool, Mapping, string, SqlCommand, string)
Deletes rows from the destination main table by comparing it, on key columns, to the temporary import table
{DestinationTableName}{tempTablePrefix}. Convenience overload of
DeleteRowsFromMainTable(bool, Dictionary<string, Mapping>, string, SqlCommand) for a single mapping.
protected static int DeleteRowsFromMainTable(bool deleteExistingRows, Mapping mapping, string extraConditions, SqlCommand sqlCommand, string tempTablePrefix)
Parameters
deleteExistingRowsboolWhen
true, deletes rows that are present in the import source; whenfalse, deletes excess rows that are not present in the import source.mappingMappingThe mapping whose destination table the rows are deleted from.
extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.sqlCommandSqlCommandThe command used to execute the delete; its
CommandTextis replaced and its connection must be open.tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
Returns
- int
The number of deleted rows.
DeleteRowsFromMainTable(bool, Dictionary<string, Mapping>, IEnumerable<Mapping>, string, SqlCommand)
Deletes rows from the destination main table, comparing it to the temporary tables of
mappings while restricting the delete to the slice of the table
conditionalMappings covers.
protected static int DeleteRowsFromMainTable(bool deleteExistingRows, Dictionary<string, Mapping> mappings, IEnumerable<Mapping> conditionalMappings, string extraConditions, SqlCommand sqlCommand)
Parameters
deleteExistingRowsboolWhen
true, deletes rows that are present in the import source; whenfalse, deletes excess rows that are not present in it.mappingsDictionary<string, Mapping>Temporary table prefixes and their mappings, forming the combined source dataset a row is compared against. All mappings must share the same destination table.
conditionalMappingsIEnumerable<Mapping>The mappings whose conditionals scope the delete; pass
mappings.Valueswhen every mapping drives the delete.extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.sqlCommandSqlCommandThe command used to execute the delete; its
CommandTextis replaced and its connection must be open.
Returns
- int
The number of deleted rows.
Remarks
The two sets differ when some of the mappings sharing a destination table must not drive a delete - because
they imported no rows, are inactive, or opted out of removing missing rows. Such a mapping is still listed in
mappings, so the rows it imported count as present in the source and are not deleted on a
sibling mapping's behalf, but it is left out of conditionalMappings, so it does not widen
the slice of the destination table the delete may touch.
Exceptions
- InvalidOperationException
Thrown when the delete fails; the message includes the executed SQL.
DeleteRowsFromMainTable(bool, Dictionary<string, Mapping>, string, SqlCommand)
Deletes rows from the destination main table by comparing it, on key columns, to one or more temporary import
tables. The delete runs in batches of 100,000 rows until no rows remain, applying the mappings' conditionals
as one combined parameterized condition, and the command timeout is raised to at least the configured database timeout
(minimum 360 seconds). Returns 0 without executing anything when mappings,
sqlCommand or extraConditions is null or the mapping dictionary
is empty.
protected static int DeleteRowsFromMainTable(bool deleteExistingRows, Dictionary<string, Mapping> mappings, string extraConditions, SqlCommand sqlCommand)
Parameters
deleteExistingRowsboolWhen
true, deletes rows that are present in the import source; whenfalse, deletes excess rows that are not present in the import source.mappingsDictionary<string, Mapping>Temporary table prefixes and their mappings; use multiple entries to extend the exists/not-exists check when several temporary tables target the same main table. All mappings must share the same destination table, and are then treated as one combined source dataset - see GetCombinedConditionalsSql(IEnumerable<Mapping>, ICollection<SqlParameter>).
extraConditionsstringAn additional WHERE fragment (starting with
and) filtering the rows considered for deletion; pass an empty string for none.sqlCommandSqlCommandThe command used to execute the delete; its
CommandTextis replaced and its connection must be open.
Returns
- int
The number of deleted rows.
Exceptions
- InvalidOperationException
Thrown when the delete fails; the message includes the executed SQL.
GetBulkCopyTimeout()
The timeout in seconds to apply to BulkCopyTimeout. Bulk copies used to run
with no timeout at all (BulkCopyTimeout = 0), so a wedged connection could hang an integration
job forever. The default is bounded instead: the global setting
/Globalsettings/DataIntegration/BulkCopyTimeout (seconds, default 3600); a negative value
restores the unbounded behavior.
protected static int GetBulkCopyTimeout()
Returns
GetExtraConditions(Mapping, string, string, SqlCommand)
Builds the shop/language filter condition for the given destination table, binding the shop and language
values as SqlParameters on sqlCommand instead of concatenating them into the SQL text.
protected static string GetExtraConditions(Mapping mapping, string shop, string languageId, SqlCommand sqlCommand)
Parameters
mappingMappingMapping
shopstringShop ID
languageIdstringLanguage ID
sqlCommandSqlCommandCommand the resulting condition will be executed on; shop/language parameters are added to it
Returns
GetMoveDataToMainTableException(Exception, SqlCommand, Mapping, string, List<string>)
Builds the exception thrown when merging the temporary table into the main table fails. Delegates to GetMoveDataToMainTableException(Exception, SqlCommand, Mapping, string, List<string>, string?, string?) using the mapping's destination table for both table names.
protected static Exception GetMoveDataToMainTableException(Exception ex, SqlCommand sqlCommand, Mapping mapping, string tempTablePrefix, List<string> insertColumns)
Parameters
exExceptionThe failure that occurred during the merge.
sqlCommandSqlCommandThe command the merge was executed with; reused to look up failed rows.
mappingMappingThe mapping that was being merged.
tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
insertColumnsList<string>The bracket-quoted columns of the insert statement; used to select the failed rows for the message.
Returns
- Exception
An InvalidOperationException describing the failure, wrapping
ex.
GetMoveDataToMainTableException(Exception, SqlCommand, Mapping, string, List<string>, string?, string?)
Builds the exception thrown when merging the temporary table into the main table fails. The message contains the table names, the original error and the executed SQL; when the failure is a foreign key violation (SQL Server error 547), the temporary table is queried and the rows violating the constraint are appended to the message.
protected static Exception GetMoveDataToMainTableException(Exception ex, SqlCommand sqlCommand, Mapping mapping, string tempTablePrefix, List<string> insertColumns, string? sourceTableName, string? destinationTableName)
Parameters
exExceptionThe failure that occurred during the merge.
sqlCommandSqlCommandThe command the merge was executed with; reused to look up failed rows.
mappingMappingThe mapping that was being merged.
tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
insertColumnsList<string>The bracket-quoted columns of the insert statement; used to select the failed rows for the message.
sourceTableNamestringThe table name to report as the merge source; the mapping's destination table name when
nullor empty.destinationTableNamestringThe table name to report as the merge destination; the mapping's destination table name when
nullor empty.
Returns
- Exception
An InvalidOperationException describing the failure, wrapping
ex.
HasIdentity(ColumnMappingCollection)
Determines whether any of the column mappings targets an identity destination column, in which case inserts
into the main table must be wrapped in identity_insert.
protected static bool HasIdentity(ColumnMappingCollection mappings)
Parameters
mappingsColumnMappingCollectionThe column mappings to inspect.
Returns
- bool
truewhen a mapping targets an identity column; otherwisefalse.
HasIdentity(Mapping)
Determines whether any active column mapping targets an identity destination column, in which case inserts
into the main table must be wrapped in identity_insert.
protected static bool HasIdentity(Mapping mapping)
Parameters
mappingMappingThe mapping whose column mappings are inspected.
Returns
- bool
truewhen an active mapping targets an identity column; otherwisefalse.
MoveDataToMainTable(Mapping, SqlCommand, SqlTransaction, string)
Merges the temporary import table into the destination main table (update existing rows, insert new rows). Legacy overload that delegates to MoveDataToMainTable(Mapping, SqlCommand, SqlTransaction, string, bool, bool) and discards the row count.
protected static void MoveDataToMainTable(Mapping mapping, SqlCommand sqlCommand, SqlTransaction sqlTransaction, string tempTablePrefix)
Parameters
mappingMappingThe mapping whose active column mappings define the merged columns and keys.
sqlCommandSqlCommandThe command used to execute the merge; its
CommandTextand transaction are replaced.sqlTransactionSqlTransactionThe transaction to run the merge in.
tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
MoveDataToMainTable(Mapping, SqlCommand, SqlTransaction, string, bool)
Merges the temporary import table into the destination main table. Legacy overload that delegates to MoveDataToMainTable(Mapping, SqlCommand, SqlTransaction, string, bool, bool) and discards the row count.
protected static void MoveDataToMainTable(Mapping mapping, SqlCommand sqlCommand, SqlTransaction sqlTransaction, string tempTablePrefix, bool updateOnly)
Parameters
mappingMappingThe mapping whose active column mappings define the merged columns and keys.
sqlCommandSqlCommandThe command used to execute the merge; its
CommandTextand transaction are replaced.sqlTransactionSqlTransactionThe transaction to run the merge in.
tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
updateOnlyboolWhen
true, only updates existing rows and skips the insert of new rows.
MoveDataToMainTable(Mapping, SqlCommand, SqlTransaction, string, bool, bool)
Merges the temporary import table into the destination main table: existing rows — matched on the key
columns — are updated, and rows without a match are inserted, wrapping the insert in
identity_insert when an identity column is mapped. Called by the writer after all rows have been
bulk-copied into the temporary table, typically from its close/finish phase.
protected static int MoveDataToMainTable(Mapping mapping, SqlCommand sqlCommand, SqlTransaction sqlTransaction, string tempTablePrefix, bool updateOnly, bool insertOnly)
Parameters
mappingMappingThe mapping whose active column mappings define the merged columns and keys.
sqlCommandSqlCommandThe command used to execute the merge; its
CommandTextand transaction are replaced, and its connection is opened when not already open.sqlTransactionSqlTransactionThe transaction to run the merge in.
tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
updateOnlyboolWhen
true, only updates existing rows and skips the insert of new rows.insertOnlyboolWhen
true, only inserts new rows and skips the update of existing rows.
Returns
- int
The number of updated and inserted rows.
Exceptions
- InvalidOperationException
Thrown when the merge fails; see GetMoveDataToMainTableException(Exception, SqlCommand, Mapping, string, List<string>).
- DataException
Thrown when no update or insert statement could be built from the column mappings, which indicates that nothing would be imported.
MoveDataToMainTable(SqlCommand, Mapping, SqlTransaction, string)
Merges the temporary import table into the destination main table (update existing rows, insert new rows). Delegates to MoveDataToMainTable(Mapping, SqlCommand, SqlTransaction, string, bool, bool).
protected static int MoveDataToMainTable(SqlCommand sqlCommand, Mapping mapping, SqlTransaction sqlTransaction, string tempTablePrefix)
Parameters
sqlCommandSqlCommandThe command used to execute the merge; its
CommandTextand transaction are replaced.mappingMappingThe mapping whose active column mappings define the merged columns and keys.
sqlTransactionSqlTransactionThe transaction to run the merge in.
tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
Returns
- int
The number of updated and inserted rows.
MoveDataToMainTable(SqlCommand, Mapping, SqlTransaction, string, bool)
Merges the temporary import table into the destination main table. Delegates to MoveDataToMainTable(Mapping, SqlCommand, SqlTransaction, string, bool, bool).
protected static int MoveDataToMainTable(SqlCommand sqlCommand, Mapping mapping, SqlTransaction sqlTransaction, string tempTablePrefix, bool updateOnly)
Parameters
sqlCommandSqlCommandThe command used to execute the merge; its
CommandTextand transaction are replaced.mappingMappingThe mapping whose active column mappings define the merged columns and keys.
sqlTransactionSqlTransactionThe transaction to run the merge in.
tempTablePrefixstringThe suffix appended to the destination table name to form the temporary table name.
updateOnlyboolWhen
true, only updates existing rows and skips the insert of new rows.
Returns
- int
The number of updated and inserted rows.
SetParameter(SqlCommand, string, string)
Adds a SqlParameter to sqlCommand, or updates its value if a parameter with
the same name was already added (e.g. by a previous call for the same mapping).
protected static void SetParameter(SqlCommand sqlCommand, string name, string value)
Parameters
sqlCommandSqlCommandnamestringvaluestring
SqlBulkCopierWriteToServer(SqlBulkCopy, DataTable, bool, Mapping, ILogger?)
Bulk-copies the buffered rows to the server, translating bulk copy failures into diagnostics. On failure the
individual failing rows are identified (including column-length violations) and either skipped and logged —
when skipFailingRows is true — or rethrown as an
InvalidOperationException whose message lists the failed rows.
protected static int SqlBulkCopierWriteToServer(SqlBulkCopy sqlBulkCopy, DataTable tableToWrite, bool skipFailingRows, Mapping currentMapping, ILogger? logger)
Parameters
sqlBulkCopySqlBulkCopyThe configured bulk copier targeting the temporary table.
tableToWriteDataTableThe rows to write.
skipFailingRowsboolWhen
true, failing rows are skipped and counted instead of failing the import.currentMappingMappingThe mapping being written; used to resolve destination column limits when diagnosing failures.
loggerILoggerThe logger that receives the skipped-row message; may be
null.
Returns
- int
The number of skipped rows; 0 when the bulk copy succeeded.
Exceptions
- InvalidOperationException
Thrown when the bulk copy fails and
skipFailingRowsisfalse.