Partilhar via


Como: Configurar a sincronização de dados em um aplicativo

If your application requires data from a remote database that does not have to be continuously retrieved from the database (or that is not always available), you can use a local database to store the data on the client computer with your application.

For example, consider an inventory application that uses data from several tables in a database. The number of items in stock for any individual part is an important piece of data that continually changes, so the application should always reflect the current values in the database. However, the application also displays a list of valid shipping companies that rarely changes. These valid shipping companies are stored in the Shippers table and do not have to be retrieved every time data is queried from the database. If you store this Shippers table in a local database cache, you can decrease the number of unnecessary roundtrips your application has to make to the remote database. Consider storing data that changes infrequently (or that changes on a known schedule) in a local database cache.

The local database cache uses a SQL Server Compact 3.5 database to store data locally. You can use an existing SQL Server Compact 3.5 database as the local database cache. If you do not yet have a local database, you can set the Configure Data Synchronization dialog box to create a new local database.

After you add a local database to your application and complete the Configure Data Synchronization dialog box, you still have to add code to your application to initiate the synchronization. After you successfully synchronize the data, you must also add code to refill the table in the dataset from the local database.

ObservaçãoObservação

The Configure Data Synchronization dialog box provides the ability to configure Microsoft Synchronization Services for ADO.NET for download scenarios only. Isso significa que, depois de configurar a sincronização de dados usando o Configurar sincronização de dados caixa de diálogo, chamada Microsoft.Synchronization.Data.SyncAgent.Synchronize somente irá atualizar o banco de dados local com alterações encontradas no banco de dados remoto. Changes made to the data on the local database will not be uploaded to the remote database. Depois de configurar a sincronização de dados usando o Configurar sincronização de dados caixa de diálogo, você pode programaticamente enable carregamentos (sincronização bidirecional) durante a sincronização. Para obter mais informações, consulte o Como: Configurar um Local e remoto a banco de dados para sincronização bidirecional.

Adding a Local Database Cache to a Project

You can configure applications to cache data locally by adding a .sync file to your project and configuring it by using the Configure Data Synchronization dialog box. Você pode adicionar os arquivos. Sync para projetos usando o Caixa de diálogo Add New Item.

The following procedure provides the basic steps involved in configuring data synchronization. Para obter exemplos que usam os dados reais, consulte o Demonstra Passo a passo: Criando um aplicativo ocasionalmente conectado.

ObservaçãoObservação

Seu computador pode mostrar nomes ou locais diferentes para alguns dos elementos da interface do usuário do Visual Studio nas instruções a seguir. A edição do Visual Studio que você possui e as configurações que você usa determinam esses elementos. Para obter mais informações, consulte Configurações do Visual Studio.

To configure data synchronization

  1. No menu Project, clique em Add New Item.

  2. Clique no modelo Local Database Cache.

  3. Either provide an alternative name or keep the default name of LocalDataCache1.sync.

  4. Clique em Adicionar.

    The .sync file is added to the project and the Configure Data Synchronization dialog box opens.

  5. Set the Server connection to the remote database that you want to connect to.

  6. Definir o conexão de cliente para o local SQL Server Compact 3.5 banco de dados que irá armazenar seus dados localmente. Se você não tiver um banco de dados local, você pode deixar a configuração padrão de DatabaseName. sdf (novo) para criar um novo banco de dados do projeto. The name of the new database will be based on the name of the database in the Server connection.

    ObservaçãoObservação

    The OK button is disabled by default and is enabled after adding a table to the Cached Tables area.

  7. Click Add to open the Configure Tables for Offline Use dialog box and select and configure the database tables to add to the local database cache.

  8. Select the database tables you want to add to the local database cache, and configure each of the following settings:

    • Data to download:

      New and incremental changes after first synchronization

      This setting retrieves records from the server that have been modified since the last time data was synchronized. The first time synchronization is called, the entire table will be downloaded.

      Entire table each time

      This setting drops the local table and replaces it with the version on the server.

    • Compare updates using

      Set this to the column name in the selected table that is used to track when the last update of a record was made. By default, any column that is defined as a datetime or timestamp will appear in this list. If the table does not contain a column that is used to track modified records, you can leave the default setting of LastEditDate (new), which will create the tracking column for you.

    • Compare inserts using

      Set this to the column name in the selected table that is used to track when new records are added to the table. By default, any column that is defined as a datetime or timestamp will appear in this list. If the table does not contain a column that is used to track new records, you can leave the default setting of CreationDate (new), which will create the tracking column for you.

    • Move deleted items to

      Set this to the table on the database server that is used to store deleted records. By default, any table that is named tableName_Deleted or tableName_Tombstone will appear in this list. If the database does not contain a table for storing deleted items, you can leave the default setting of tableName**_Tombstone (new)**, which will create the deleted items table for you.

      ObservaçãoObservação

      Configure these settings for each table that you are configuring for offline use.

  9. By default, the Script Generation options are automatically set to generate and run the server-side scripts that are used to configure the database server. If you do not need these scripts, or if you do not have access to the database server, you can clear either option and manually run the scripts or modify your tables. If no changes are required on the server, no scripts will be generated.

    ObservaçãoObservação

    These scripts add the tracking columns to the selected tables, create the tables for storing deleted items, and add some triggers that you must have to keep track of the Inserts, Updates, and Deletes on tables that are set up for local caching.

  10. Clique em OK.

  11. Click Show Code Example to open the Code Example dialog box, which provides a code snippet that starts the synchronization process. You can copy this snippet to the clipboard and insert into your program.

  12. Optionally, set the Advanced options.

    The Advanced options on the Configure Data Synchronization dialog box provide settings that enable you to control whether tables are synchronized separately or in a single transaction. The options also enable code separation for n-tier applications.

    1. Synchronize tables in a single transaction. By default, this is not checked and all tables are synchronized individually. If errors are encountered, only tables with errors have their changes rolled back. If you check this option, all tables are synchronized in a single transaction. If errors are encountered, all changes for all tables are rolled back.

    2. Create synchronization components. By default, synchronization components are generated for both the client and the server. You can set this option to Client only or Server only to meet your application requirements.

    3. Server project location. By default, the synchronization components for the server will be generated in the current project. Set this option to generate synchronization components for the server into any Visual Basic or Visual C# project in the solution.

    4. Client project location. By default, the synchronization components for the client will be generated into the current project. Set this option to generate synchronization components for the client into any Visual Basic or Visual C# project in the solution.

After you complete the Configure Data Synchronization dialog box, you have to add code to your application to initiate the synchronization.

ObservaçãoObservação

Synchronizing data updates the local database, not the table in the dataset or any other object in your application. Lembre-se de recarregar a fonte de dados do seu aplicativo com os dados atualizados do banco de dados local. Por exemplo, chame o método TableAdapter.Fill para carregar a tabela de dados do seu DataSet com os dados atualizados do banco de dados local.

To initiate synchronization

  • If you copied the code from the Code Example dialog box in the previous section, you can just paste it into your application. Otherwise, you can insert the following code anywhere in your application where you want to initiate the synchronization process:

Consulte também

Tarefas

Demonstra Passo a passo: Criando um aplicativo ocasionalmente conectado

Demonstra Passo a passo: Implantando um aplicativo ocasionalmente conectado do cliente com o banco de dados Local

Conceitos

Visão geral sobre aplicativos ocasionalmente conectados

Outros recursos

Aplicativos ocasionalmente conectados (cache de banco de dados Local)