Класс SyncAdapter

Представляет набор команд данных, которые используются для получения сведений о схеме, а также для получения и применения изменений в базе данных сервера.

Пространство имен: Microsoft.Synchronization.Data.Server
Сборка: Microsoft.Synchronization.Data.Server (в microsoft.synchronization.data.server.dll)

Синтаксис

'Декларация
Public Class SyncAdapter
'Применение
Dim instance As SyncAdapter
public class SyncAdapter
public ref class SyncAdapter
public class SyncAdapter
public class SyncAdapter

Замечания

Адаптер обработки данных SyncAdapter обеспечивает взаимодействие между DbServerSyncProvider и базой данных сервера. Адаптер синхронизации, который является аналогом адаптера обработки данных в ADO.NET, определяется для каждой синхронизируемой таблицы. Адаптер синхронизации передает службе синхронизации сервера определенные команды, необходимые для взаимодействия с базой данных сервера, например InsertCommand, которая выполняет операции вставки из клиентской базы данных в базу данных сервера. Поскольку адаптеры синхронизации используют объект ADO.NETDbCommand, может быть использована любая структура команд, совместимая с ADO.NET. Это относится к встроенным инструкциям Transact-SQL, хранимым процедурам, представлениям, функциям и так далее. Командам требуется только один результат, определяющий структуру и данные, которые должны быть переданы и применены.

Пример

В следующем примере кода создается объект SyncAdapter для таблицы Customer. Таблица настроена для двунаправленной синхронизации с обнаружением конфликтов, поэтому указаны все допустимые команды. Для выборки изменений на сервере команды заданы в виде встроенного Transact-SQL. Команды для применения изменений на сервере являются хранимыми процедурами, определение которых приведено в разделе Инструкции по сценариям установки для поставщика базы данных. Дополнительные сведения о командах адаптера см. в разделе Как задать синхронизацию моментальными снимками, с загрузкой, с передачей и двунаправленную. Чтобы просмотреть этот код в контексте полного примера, см. раздел Как обрабатывать конфликты и ошибки в данных.

SyncAdapter customerSyncAdapter = new SyncAdapter("Customer");

//This command is used if @sync_row_count returns
//0 when changes are applied to the server.
SqlCommand customerUpdateConflicts = new SqlCommand();
customerUpdateConflicts.CommandText =
    "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " +
    "FROM Sales.Customer " +
    "WHERE CustomerId = @CustomerId";
customerUpdateConflicts.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier);
customerUpdateConflicts.Connection = serverConn;
customerSyncAdapter.SelectConflictUpdatedRowsCommand = customerUpdateConflicts;

//This command is used if the server provider cannot find
//a row in the base table.
SqlCommand customerDeleteConflicts = new SqlCommand();
customerDeleteConflicts.CommandText =
    "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " +
    "FROM Sales.Customer_Tombstone " +
    "WHERE CustomerId = @CustomerId";
customerDeleteConflicts.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier);
customerDeleteConflicts.Connection = serverConn;
customerSyncAdapter.SelectConflictDeletedRowsCommand = customerDeleteConflicts;

//Select inserts from the server.
SqlCommand customerIncrInserts = new SqlCommand();
customerIncrInserts.CommandText =
    "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " +
    "FROM Sales.Customer " +
    "WHERE (InsertTimestamp > @sync_last_received_anchor " +
    "AND InsertTimestamp <= @sync_new_received_anchor " +
    "AND InsertId <> @sync_client_id)";
customerIncrInserts.Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp);
customerIncrInserts.Parameters.Add("@" + SyncSession.SyncNewReceivedAnchor, SqlDbType.Timestamp);
customerIncrInserts.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier);
customerIncrInserts.Connection = serverConn;
customerSyncAdapter.SelectIncrementalInsertsCommand = customerIncrInserts;

//Apply inserts to the server.
SqlCommand customerInserts = new SqlCommand();
customerInserts.CommandType = CommandType.StoredProcedure;
customerInserts.CommandText = "usp_CustomerApplyInsert";
customerInserts.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier);
customerInserts.Parameters.Add("@" + SyncSession.SyncForceWrite, SqlDbType.Bit); 
customerInserts.Parameters.Add("@" + SyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output;
customerInserts.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier);
customerInserts.Parameters.Add("@CustomerName", SqlDbType.NVarChar);
customerInserts.Parameters.Add("@SalesPerson", SqlDbType.NVarChar);
customerInserts.Parameters.Add("@CustomerType", SqlDbType.NVarChar);
customerInserts.Connection = serverConn;
customerSyncAdapter.InsertCommand = customerInserts;


//Select updates from the server.
SqlCommand customerIncrUpdates = new SqlCommand();
customerIncrUpdates.CommandText =
    "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " +
    "FROM Sales.Customer " +
    "WHERE (UpdateTimestamp > @sync_last_received_anchor " +
    "AND UpdateTimestamp <= @sync_new_received_anchor " +
    "AND UpdateId <> @sync_client_id " +
    "AND NOT (InsertTimestamp > @sync_last_received_anchor " +
    "AND InsertId <> @sync_client_id))";
customerIncrUpdates.Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp);
customerIncrUpdates.Parameters.Add("@" + SyncSession.SyncNewReceivedAnchor, SqlDbType.Timestamp);
customerIncrUpdates.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier);
customerIncrUpdates.Connection = serverConn;
customerSyncAdapter.SelectIncrementalUpdatesCommand = customerIncrUpdates;

//Apply updates to the server.
SqlCommand customerUpdates = new SqlCommand();
customerUpdates.CommandType = CommandType.StoredProcedure;
customerUpdates.CommandText = "usp_CustomerApplyUpdate";
customerUpdates.Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp);
customerUpdates.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier);
customerUpdates.Parameters.Add("@" + SyncSession.SyncForceWrite, SqlDbType.Bit);            
customerUpdates.Parameters.Add("@" + SyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output;
customerUpdates.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier);
customerUpdates.Parameters.Add("@CustomerName", SqlDbType.NVarChar);
customerUpdates.Parameters.Add("@SalesPerson", SqlDbType.NVarChar);
customerUpdates.Parameters.Add("@CustomerType", SqlDbType.NVarChar);
customerUpdates.Connection = serverConn;
customerSyncAdapter.UpdateCommand = customerUpdates;


//Select deletes from the server.
SqlCommand customerIncrDeletes = new SqlCommand();
customerIncrDeletes.CommandText =
    "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " +
    "FROM Sales.Customer_Tombstone " +
    "WHERE (@sync_initialized = 1 " +
    "AND DeleteTimestamp > @sync_last_received_anchor " +
    "AND DeleteTimestamp <= @sync_new_received_anchor " +
    "AND DeleteId <> @sync_client_id)";
customerIncrDeletes.Parameters.Add("@" + SyncSession.SyncInitialized, SqlDbType.Bit);
customerIncrDeletes.Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp);
customerIncrDeletes.Parameters.Add("@" + SyncSession.SyncNewReceivedAnchor, SqlDbType.Timestamp);
customerIncrDeletes.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier);
customerIncrDeletes.Connection = serverConn;
customerSyncAdapter.SelectIncrementalDeletesCommand = customerIncrDeletes;

//Apply deletes to the server.
SqlCommand customerDeletes = new SqlCommand();
customerDeletes.CommandType = CommandType.StoredProcedure;
customerDeletes.CommandText = "usp_CustomerApplyDelete";
customerDeletes.Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp);
customerDeletes.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier);
customerDeletes.Parameters.Add("@" + SyncSession.SyncForceWrite, SqlDbType.Bit);           
customerDeletes.Parameters.Add("@" + SyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output;
customerDeletes.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier);
customerDeletes.Connection = serverConn;
customerSyncAdapter.DeleteCommand = customerDeletes;


//Add the SyncAdapter to the server synchronization provider.
this.SyncAdapters.Add(customerSyncAdapter);
Dim customerSyncAdapter As New SyncAdapter("Customer")

'This command is used if @sync_row_count returns
'0 when changes are applied to the server.
Dim customerUpdateConflicts As New SqlCommand()
With customerUpdateConflicts
    .CommandText = _
        "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " _
      & "FROM Sales.Customer " + "WHERE CustomerId = @CustomerId"
    .Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier)
    .Connection = serverConn
End With
customerSyncAdapter.SelectConflictUpdatedRowsCommand = customerUpdateConflicts

'This command is used if the server provider cannot find
'a row in the base table.
Dim customerDeleteConflicts As New SqlCommand()
With customerDeleteConflicts
    .CommandText = _
        "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " _
      & "FROM Sales.Customer_Tombstone " + "WHERE CustomerId = @CustomerId"
    .Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier)
    .Connection = serverConn
End With
customerSyncAdapter.SelectConflictDeletedRowsCommand = customerDeleteConflicts

'Select inserts from the server.
Dim customerIncrInserts As New SqlCommand()
With customerIncrInserts
    .CommandText = _
        "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " _
      & "FROM Sales.Customer " _
      & "WHERE (InsertTimestamp > @sync_last_received_anchor " _
      & "AND InsertTimestamp <= @sync_new_received_anchor " _
      & "AND InsertId <> @sync_client_id)"
    .Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp)
    .Parameters.Add("@" + SyncSession.SyncNewReceivedAnchor, SqlDbType.Timestamp)
    .Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier)
    .Connection = serverConn
End With
customerSyncAdapter.SelectIncrementalInsertsCommand = customerIncrInserts

'Apply inserts to the server.
Dim customerInserts As New SqlCommand()
customerInserts.CommandType = CommandType.StoredProcedure
customerInserts.CommandText = "usp_CustomerApplyInsert"
customerInserts.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier)
customerInserts.Parameters.Add("@" + SyncSession.SyncForceWrite, SqlDbType.Bit)
customerInserts.Parameters.Add("@" + SyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output
customerInserts.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier)
customerInserts.Parameters.Add("@CustomerName", SqlDbType.NVarChar)
customerInserts.Parameters.Add("@SalesPerson", SqlDbType.NVarChar)
customerInserts.Parameters.Add("@CustomerType", SqlDbType.NVarChar)
customerInserts.Connection = serverConn
customerSyncAdapter.InsertCommand = customerInserts


'Select updates from the server.
Dim customerIncrUpdates As New SqlCommand()
With customerIncrUpdates
    .CommandText = _
        "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " _
      & "FROM Sales.Customer " _
      & "WHERE (UpdateTimestamp > @sync_last_received_anchor " _
      & "AND UpdateTimestamp <= @sync_new_received_anchor " _
      & "AND UpdateId <> @sync_client_id " _
      & "AND NOT (InsertTimestamp > @sync_last_received_anchor " _
      & "AND InsertId <> @sync_client_id))"
    .Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp)
    .Parameters.Add("@" + SyncSession.SyncNewReceivedAnchor, SqlDbType.Timestamp)
    .Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier)
    .Connection = serverConn
End With
customerSyncAdapter.SelectIncrementalUpdatesCommand = customerIncrUpdates

'Apply updates to the server.
Dim customerUpdates As New SqlCommand()
customerUpdates.CommandType = CommandType.StoredProcedure
customerUpdates.CommandText = "usp_CustomerApplyUpdate"
customerUpdates.Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp)
customerUpdates.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier)
customerUpdates.Parameters.Add("@" + SyncSession.SyncForceWrite, SqlDbType.Bit)
customerUpdates.Parameters.Add("@" + SyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output
customerUpdates.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier)
customerUpdates.Parameters.Add("@CustomerName", SqlDbType.NVarChar)
customerUpdates.Parameters.Add("@SalesPerson", SqlDbType.NVarChar)
customerUpdates.Parameters.Add("@CustomerType", SqlDbType.NVarChar)
customerUpdates.Connection = serverConn
customerSyncAdapter.UpdateCommand = customerUpdates


'Select deletes from the server.
Dim customerIncrDeletes As New SqlCommand()
With customerIncrDeletes
    .CommandText = _
        "SELECT CustomerId, CustomerName, SalesPerson, CustomerType " _
      & "FROM Sales.Customer_Tombstone " _
      & "WHERE (@sync_initialized = 1 " _
      & "AND DeleteTimestamp > @sync_last_received_anchor " _
      & "AND DeleteTimestamp <= @sync_new_received_anchor " _
      & "AND DeleteId <> @sync_client_id)"
    .Parameters.Add("@" + SyncSession.SyncInitialized, SqlDbType.Bit)
    .Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp)
    .Parameters.Add("@" + SyncSession.SyncNewReceivedAnchor, SqlDbType.Timestamp)
    .Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier)
    .Connection = serverConn
End With
customerSyncAdapter.SelectIncrementalDeletesCommand = customerIncrDeletes

'Apply deletes to the server.
Dim customerDeletes As New SqlCommand()
customerDeletes.CommandType = CommandType.StoredProcedure
customerDeletes.CommandText = "usp_CustomerApplyDelete"
customerDeletes.Parameters.Add("@" + SyncSession.SyncLastReceivedAnchor, SqlDbType.Timestamp)
customerDeletes.Parameters.Add("@" + SyncSession.SyncClientId, SqlDbType.UniqueIdentifier)
customerDeletes.Parameters.Add("@" + SyncSession.SyncForceWrite, SqlDbType.Bit)
customerDeletes.Parameters.Add("@" + SyncSession.SyncRowCount, SqlDbType.Int).Direction = ParameterDirection.Output
customerDeletes.Parameters.Add("@CustomerId", SqlDbType.UniqueIdentifier)
customerDeletes.Connection = serverConn
customerSyncAdapter.DeleteCommand = customerDeletes


'Add the SyncAdapter to the server synchronization provider.
Me.SyncAdapters.Add(customerSyncAdapter)

Иерархия наследования

System.Object
  Microsoft.Synchronization.Data.Server.SyncAdapter

Многопоточное использование

Все общие статические члены (Shared в Visual Basic) можно использовать в многопоточных операциях. Безопасная многопоточная работа с членами экземпляров типа не гарантируется.

См. также

Справочник

Элементы SyncAdapter
Пространство имен Microsoft.Synchronization.Data.Server