

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# Driver Amazon QLDB per.NET
driver DI.NET

**Importante**  
Avviso di fine del supporto: i clienti esistenti potranno utilizzare Amazon QLDB fino alla fine del supporto, il 31/07/2025. Per ulteriori dettagli, consulta [Migrare un registro Amazon QLDB su Amazon Aurora PostgreSQL](https://aws.amazon.com/blogs/database/migrate-an-amazon-qldb-ledger-to-amazon-aurora-postgresql/).

Per utilizzare i dati nel registro, puoi connetterti ad Amazon QLDB dall'applicazione Microsoft.NET utilizzando un driver fornito. AWS Il driver è indirizzato a **.NET Standard 2.0**. Più specificamente, supporta **.NET Core (LTS) 2.1\$1 **e.NET** Framework 4.5.2\$1**. Per informazioni sulla compatibilità, [vedi.NET Standard](https://docs.microsoft.com/en-us/dotnet/standard/net-standard) nel sito *Microsoft Docs.*

Consigliamo vivamente di utilizzare lo strumento di *mappatura degli oggetti Ion per* evitare completamente la necessità di effettuare la conversione manuale tra i tipi di Amazon Ion e i tipi nativi di C\$1.

Negli argomenti seguenti viene descritto come iniziare a utilizzare il driver QLDB per.NET.

**Topics**
+ [

## Risorse per i driver
](#getting-started.dotnet.resources)
+ [

## Prerequisiti
](#getting-started.dotnet.prereqs)
+ [

## Installazione
](#getting-started.dotnet.install)
+ [Tutorial di avvio rapido](driver-quickstart-dotnet.md)
+ [Riferimento al libro di cucina](driver-cookbook-dotnet.md)

## Risorse per i driver


Per ulteriori informazioni sulle funzionalità supportate dal driver.NET, consulta le seguenti risorse:
+ [Documentazione di riferimento dell'API](https://amazon-qldb-docs.s3.amazonaws.com/drivers/dotnet/1.4.1/api/Amazon.QLDB.Driver.html)
+ [Codice sorgente del driver (GitHub)](https://github.com/awslabs/amazon-qldb-driver-dotnet)
+ [Codice sorgente dell'applicazione di esempio (GitHub)](https://github.com/aws-samples/amazon-qldb-dmv-sample-dotnet)
+ [Ricettario Amazon Ion](http://amzn.github.io/ion-docs/guides/cookbook.html)
+ [Mappatore di oggetti Ion () GitHub](https://github.com/amzn/ion-object-mapper-dotnet)

## Prerequisiti


Prima di iniziare a utilizzare il driver QLDB per.NET, è necessario effettuare le seguenti operazioni:

1. Segui le istruzioni di AWS configurazione riportate in. [Accesso ad Amazon QLDB](accessing.md) Questo include gli output seguenti:

   1. Iscriviti a AWS.

   1. Crea un utente con le autorizzazioni QLDB appropriate.

   1. Concedi l'accesso programmatico per lo sviluppo.

1. Scarica e installa di.NET Core SDK versione 2.1 o successiva dal sito di [download di Microsoft.NET](https://dotnet.microsoft.com/download).

1. (Facoltativo) Installa un ambiente di sviluppo integrato (IDE) a tua scelta, come Visual Studio, Visual Studio per Mac o Visual Studio Code. È possibile scaricarli dal sito di [Microsoft Visual Studio](https://visualstudio.microsoft.com/).

1. Configura il tuo ambiente di sviluppo per [AWS SDK per .NET](https://aws.amazon.com/sdk-for-net):

   1. Configura le tue AWS credenziali. Ti consigliamo di creare un file di credenziali condiviso.

      *Per istruzioni, consulta [Configurazione delle AWS credenziali utilizzando un file di credenziali](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-config-creds.html#creds-file) nella Guida per gli sviluppatori.AWS SDK per .NET *

   1. Imposta il tuo valore predefinito. Regione AWS Per sapere come, vedi [Regione AWS selezione](https://docs.aws.amazon.com/sdk-for-net/latest/developer-guide/net-dg-region-selection.html).

      Per un elenco completo delle regioni disponibili, consulta gli [endpoint e le quote di Amazon QLDB](https://docs.aws.amazon.com/general/latest/gr/qldb.html) nel. *Riferimenti generali di AWS*

Successivamente, puoi configurare un'applicazione di esempio di base ed eseguire esempi di codice breve, oppure puoi installare il driver in un progetto.NET esistente.
+ Per installare il driver QLDB e AWS SDK per .NET poi in un progetto esistente, procedi con. [Installazione](#getting-started.dotnet.install)
+ Per configurare un progetto ed eseguire brevi esempi di codice che illustrano le transazioni di dati di base su un registro, consulta il. [Tutorial di avvio rapido](driver-quickstart-dotnet.md)

## Installazione


Usa il gestore di NuGet pacchetti per installare il driver QLDB per.NET. Ti consigliamo di utilizzare Visual Studio o un IDE a tua scelta per aggiungere dipendenze al progetto. Il nome del pacchetto driver è [Amazon.QLDB.Driver](https://www.nuget.org/packages/amazon.qldb.driver).

Ad esempio, in Visual Studio, apri la **console NuGet Package Manager** nel menu **Strumenti**. Quindi, inserisci il seguente comando al `PM>` prompt.

```
PM> Install-Package Amazon.QLDB.Driver
```

L'installazione del driver installa anche le sue dipendenze, inclusi i pacchetti Amazon [Ion e AWS SDK per .NET Amazon.](ion.md)

### Installa lo strumento di mappatura degli oggetti Ion


La versione 1.3.0 del driver QLDB per.NET introduce il supporto per l'accettazione e la restituzione di tipi di dati C\$1 nativi senza la necessità di utilizzare Amazon Ion. Per utilizzare questa funzionalità, aggiungi il seguente pacchetto al tuo progetto.
+ [Amazon.qldb.driver.Serialization](https://www.nuget.org/packages/Amazon.QLDB.Driver.Serialization/): una libreria in grado di mappare i valori Ion su *semplici vecchi oggetti CLR* (POCO) di C\$1 e viceversa. Questo mappatore di oggetti Ion consente all'applicazione di interagire direttamente con i tipi di dati nativi C\$1 senza la necessità di lavorare con Ion. Per una breve guida su come utilizzare questa libreria, consultate il file [Serialization.md](https://github.com/awslabs/amazon-qldb-driver-dotnet/blob/master/SERIALIZATION.md) nel repository. GitHub `awslabs/amazon-qldb-driver-dotnet`

Per installare questo pacchetto, inserisci il seguente comando.

```
PM> Install-Package Amazon.QLDB.Driver.Serialization
```

Per brevi esempi di codice su come eseguire transazioni di dati di base su un registro, vedere il[Riferimento al libro di cucina](driver-cookbook-dotnet.md).

# Driver Amazon QLDB per.NET — Tutorial di avvio rapido
Tutorial di avvio rapido

**Importante**  
Avviso di fine del supporto: i clienti esistenti potranno utilizzare Amazon QLDB fino alla fine del supporto, il 31/07/2025. Per ulteriori dettagli, consulta [Migrare un registro Amazon QLDB su Amazon Aurora PostgreSQL](https://aws.amazon.com/blogs/database/migrate-an-amazon-qldb-ledger-to-amazon-aurora-postgresql/).

In questo tutorial, imparerai come configurare una semplice applicazione utilizzando il driver Amazon QLDB per.NET. Questa guida include i passaggi per l'installazione del driver e brevi esempi di operazioni di base di *creazione, lettura, aggiornamento ed eliminazione* (CRUD).

**Topics**
+ [

## Prerequisiti
](#driver-quickstart-dotnet.prereqs)
+ [

## Fase 1: Configurazione del progetto
](#driver-quickstart-dotnet.step-1)
+ [

## Fase 2: Inizializzare il driver
](#driver-quickstart-dotnet.step-2)
+ [

## Fase 3: Creare una tabella e un indice
](#driver-quickstart-dotnet.step-3)
+ [

## Fase 4: Inserimento di un documento
](#driver-quickstart-dotnet.step-4)
+ [

## Fase 5: Interrogare il documento
](#driver-quickstart-dotnet.step-5)
+ [

## Fase 6: Aggiornare il documento
](#driver-quickstart-dotnet.step-6)
+ [

## Esecuzione dell'applicazione completa
](#driver-quickstart-dotnet.complete)

## Prerequisiti


Prima di iniziare, assicuratevi di fare quanto segue:

1. Completa il driver [Prerequisiti](getting-started.dotnet.md#getting-started.dotnet.prereqs) for the .NET, se non l'hai già fatto. Ciò include la registrazione AWS, la concessione dell'accesso programmatico per lo sviluppo e l'installazione di.NET Core SDK.

1. Crea un libro mastro denominato. `quick-start`

   Per informazioni su come creare un registro, consulta [Operazioni di base per i registri Amazon QLDB](ledger-management.basics.md) o [Fase 1: Creare un nuovo libro contabile](getting-started-step-1.md) in *Guida introduttiva alla console*.

## Fase 1: Configurazione del progetto


Innanzitutto, configura il tuo progetto.NET.

1. Per creare ed eseguire un'applicazione modello, inserisci i seguenti `dotnet` comandi su un terminale come *bash* o *Command Prompt*. *PowerShell*

   ```
   $ dotnet new console --output Amazon.QLDB.QuickStartGuide
   $ dotnet run --project Amazon.QLDB.QuickStartGuide
   ```

   Questo modello crea una cartella denominata. `Amazon.QLDB.QuickStartGuide` In quella cartella, crea un progetto con lo stesso nome e un file denominato`Program.cs`. Il programma contiene codice che visualizza l'output`Hello World!`.

1. Usa il gestore di NuGet pacchetti per installare il driver QLDB per.NET. Ti consigliamo di utilizzare Visual Studio o un IDE a tua scelta per aggiungere dipendenze al tuo progetto. Il nome del pacchetto driver è [Amazon.QLDB.Driver](https://www.nuget.org/packages/amazon.qldb.driver).
   + Ad esempio, in Visual Studio, apri la **console NuGet Package Manager** nel menu **Strumenti**. Quindi, inserisci il seguente comando al `PM>` prompt.

     ```
     PM> Install-Package Amazon.QLDB.Driver
     ```
   + In alternativa, puoi inserire i seguenti comandi sul tuo terminale.

     ```
     $ cd Amazon.QLDB.QuickStartGuide
     $ dotnet add package Amazon.QLDB.Driver
     ```

   L'installazione del driver installa anche le sue dipendenze, incluse le librerie Amazon [Ion e [AWS SDK per .NET](https://aws.amazon.com/sdk-for-net)Amazon.](ion.md)

1. Installa la libreria di serializzazione del driver.

   ```
   PM> Install-Package Amazon.QLDB.Driver.Serialization
   ```

1. Apri il file `Program.cs`.

   Quindi, aggiungi in modo incrementale gli esempi di codice nei passaggi seguenti per provare alcune operazioni CRUD di base. [In alternativa, puoi saltare il step-by-step tutorial ed eseguire invece l'applicazione completa.](#driver-quickstart-dotnet.complete)

**Nota**  
**Scelta tra sincrono e asincrono APIs: il driver fornisce funzionalità sincrone** e asincrone. APIs Per le applicazioni ad alta richiesta che gestiscono più richieste senza blocchi, consigliamo di utilizzare la modalità asincrona per migliorare le prestazioni. APIs Il driver offre la funzionalità sincrona APIs come ulteriore comodità per le basi di codice esistenti scritte in modo sincrono.  
Questo tutorial include esempi di codice sincrono e asincrono. Per ulteriori informazioni su APIs, consulta il [IQldbDriver](https://amazon-qldb-docs.s3.amazonaws.com/drivers/dotnet/1.4.1/api/Amazon.QLDB.Driver.IQldbDriver.html) e le [IAsyncQldbDriver](https://amazon-qldb-docs.s3.amazonaws.com/drivers/dotnet/1.4.1/api/Amazon.QLDB.Driver.IAsyncQldbDriver.html)interfacce nella documentazione dell'API.
**Elaborazione dei dati Amazon Ion**: questo tutorial fornisce esempi di codice di elaborazione dei dati Amazon Ion utilizzando l'[object mapper Ion per](https://github.com/amzn/ion-object-mapper-dotnet) impostazione predefinita. QLDB ha introdotto il mappatore di oggetti Ion nella versione 1.3.0 del driver.NET. Ove applicabile, questo tutorial fornisce anche esempi di codice che utilizzano la [libreria Ion](https://github.com/amzn/ion-dotnet) standard come alternativa. Per ulteriori informazioni, consulta [Lavorare con Amazon Ion](driver-cookbook-dotnet.md#cookbook-dotnet.ion).

## Fase 2: Inizializzare il driver


Inizializza un'istanza del driver che si connette al registro denominato. `quick-start` Aggiungi il codice seguente al tuo `Program.cs` file.

------
#### [ Async ]

```
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;

namespace Amazon.QLDB.QuickStartGuide
{
    class Program
    {
        public class Person
        {
            public string FirstName { get; set; }

            public string LastName { get; set; }

            public int Age { get; set; }

            public override string ToString()
            {
                return FirstName + ", " + LastName + ", " + Age.ToString();
            }
        }

        static async Task Main(string[] args)
        {
            Console.WriteLine("Create the async QLDB driver");
            IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
                .WithLedger("quick-start")
                .WithSerializer(new ObjectSerializer())
                .Build();
        }
    }
}
```

------
#### [ Sync ]

```
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;

namespace Amazon.QLDB.QuickStartGuide
{
    class Program
    {
        public class Person
        {
            public string FirstName { get; set; }

            public string LastName { get; set; }

            public int Age { get; set; }

            public override string ToString()
            {
                return FirstName + ", " + LastName + ", " + Age.ToString();
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Create the sync QLDB driver");
            IQldbDriver driver = QldbDriver.Builder()
                .WithLedger("quick-start")
                .WithSerializer(new ObjectSerializer())
                .Build();
        }
    }
}
```

------

### Utilizzo della libreria Ion


------
#### [ Async ]

```
using System;
using System.Threading.Tasks;
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;
using Amazon.QLDB.Driver;
using IAsyncResult = Amazon.QLDB.Driver.IAsyncResult;

namespace Amazon.QLDB.QuickStartGuide
{
    class Program
    {
        static IValueFactory valueFactory = new ValueFactory();

        static async Task Main(string[] args)
        {
            Console.WriteLine("Create the async QLDB driver");
            IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
                .WithLedger("quick-start")
                .Build();
        }
    }
}
```

------
#### [ Sync ]

```
using System;
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;
using Amazon.QLDB.Driver;

namespace Amazon.QLDB.QuickStartGuide
{
    class Program
    {
        static IValueFactory valueFactory = new ValueFactory();

        static void Main(string[] args)
        {
            Console.WriteLine("Create the sync QLDB Driver");
            IQldbDriver driver = QldbDriver.Builder()
                .WithLedger("quick-start")
                .Build();
        }
    }
}
```

------

## Fase 3: Creare una tabella e un indice


Per il resto di questo tutorial fino al *Passaggio 6*, è necessario aggiungere i seguenti esempi di codice all'esempio di codice precedente.

In questo passaggio, il codice seguente mostra come eseguire le `CREATE INDEX` istruzioni `CREATE TABLE` e le istruzioni. Crea una tabella denominata `Person` e un indice per il `firstName` campo in quella tabella. [Gli indici](ql-reference.create-index.md) sono necessari per ottimizzare le prestazioni delle query e contribuire a limitare le eccezioni ai conflitti [OCC (Optimistic Concurrency Control)](concurrency.md).

------
#### [ Async ]

```
Console.WriteLine("Creating the table and index");

// Creates the table and the index in the same transaction.
// Note: Any code within the lambda can potentially execute multiple times due to retries.
// For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
await driver.Execute(async txn =>
{
    await txn.Execute("CREATE TABLE Person");
    await txn.Execute("CREATE INDEX ON Person(firstName)");
});
```

------
#### [ Sync ]

```
Console.WriteLine("Creating the tables and index");

// Creates the table and the index in the same transaction.
// Note: Any code within the lambda can potentially execute multiple times due to retries.
// For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
driver.Execute(txn =>
{
    txn.Execute("CREATE TABLE Person");
    txn.Execute("CREATE INDEX ON Person(firstName)");
});
```

------

## Fase 4: Inserimento di un documento


Il seguente esempio di codice mostra come eseguire un'`INSERT`istruzione. QLDB supporta il linguaggio di interrogazione [PartiQL](ql-reference.md) (compatibile con SQL) e il formato dati [Amazon](ion.md) Ion (superset di JSON).

Aggiungi il codice seguente che inserisce un documento nella tabella. `Person`

------
#### [ Async ]

```
Console.WriteLine("Inserting a document");

Person myPerson = new Person {
    FirstName = "John",
    LastName = "Doe",
    Age = 32
};

await driver.Execute(async txn =>
{
    IQuery<Person> myQuery = txn.Query<Person>("INSERT INTO Person ?", myPerson);
    await txn.Execute(myQuery);
});
```

------
#### [ Sync ]

```
Console.WriteLine("Inserting a document");

Person myPerson = new Person {
    FirstName = "John",
    LastName = "Doe",
    Age = 32
};

driver.Execute(txn =>
{
    IQuery<Person> myQuery = txn.Query<Person>("INSERT INTO Person ?", myPerson);
    txn.Execute(myQuery);
});
```

------

### Utilizzo della libreria Ion


------
#### [ Async ]

```
Console.WriteLine("Inserting a document");

// This is one way of creating Ion values. We can also use an IonLoader.
// For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion
IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("firstName", valueFactory.NewString("John"));
ionPerson.SetField("lastName", valueFactory.NewString("Doe"));
ionPerson.SetField("age", valueFactory.NewInt(32));

await driver.Execute(async txn =>
{
    await txn.Execute("INSERT INTO Person ?", ionPerson);
});
```

------
#### [ Sync ]

```
Console.WriteLine("Inserting a document");

// This is one way of creating Ion values, we can also use an IonLoader.
// For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion
IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("firstName", valueFactory.NewString("John"));
ionPerson.SetField("lastName", valueFactory.NewString("Doe"));
ionPerson.SetField("age", valueFactory.NewInt(32));

driver.Execute(txn =>
{
    txn.Execute("INSERT INTO Person ?", ionPerson);
});
```

------

**Suggerimento**  
Per inserire più documenti utilizzando una singola [INSERT](ql-reference.insert.md) istruzione, è possibile passare un parametro di tipo [Ion list](driver-working-with-ion.md#driver-ion-list) all'istruzione come segue.  

```
// people is an Ion list
txn.Execute("INSERT INTO Person ?", people);
```
Non racchiudete la variabile placeholder (`?`) tra parentesi angolari doppie (`<<...>>`) quando passate un elenco Ion. *Nelle istruzioni PartiQL manuali, le parentesi doppie angolari indicano una raccolta non ordinata nota come borsa.*

## Fase 5: Interrogare il documento


Il seguente esempio di codice mostra come eseguire un'`SELECT`istruzione.

Aggiungere il codice seguente per interrogare un documento dalla `Person` tabella.

------
#### [ Async ]

```
Console.WriteLine("Querying the table");

// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IAsyncResult<Person> selectResult = await driver.Execute(async txn =>
{
    IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
    return await txn.Execute(myQuery);
});

await foreach (Person person in selectResult)
{
    Console.WriteLine(person);
    // John, Doe, 32
}
```

------
#### [ Sync ]

```
Console.WriteLine("Querying the table");

// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IResult<Person> selectResult = driver.Execute(txn =>
{
    IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
    return txn.Execute(myQuery);
});

foreach (Person person in selectResult)
{
    Console.WriteLine(person);
    // John, Doe, 32
}
```

------

### Utilizzo della libreria Ion


------
#### [ Async ]

```
Console.WriteLine("Querying the table");

IIonValue ionFirstName = valueFactory.NewString("John");

// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IAsyncResult selectResult = await driver.Execute(async txn =>
{
    return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName);
});

await foreach (IIonValue row in selectResult)
{
    Console.WriteLine(row.GetField("firstName").StringValue);
    Console.WriteLine(row.GetField("lastName").StringValue);
    Console.WriteLine(row.GetField("age").IntValue);
}
```

------
#### [ Sync ]

```
Console.WriteLine("Querying the table");

IIonValue ionFirstName = valueFactory.NewString("John");

// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IResult selectResult = driver.Execute(txn =>
{
    return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName);
});

foreach (IIonValue row in selectResult)
{
    Console.WriteLine(row.GetField("firstName").StringValue);
    Console.WriteLine(row.GetField("lastName").StringValue);
    Console.WriteLine(row.GetField("age").IntValue);
}
```

------

Questo esempio utilizza un punto interrogativo (`?`) come segnaposto variabile per passare le informazioni del documento all'istruzione. Quando si utilizzano i segnaposto, è necessario passare un valore di tipo. `IonValue`

## Fase 6: Aggiornare il documento


Il seguente esempio di codice mostra come eseguire un'`UPDATE`istruzione.

1. Aggiungere il codice seguente che aggiorna un documento nella `Person` tabella aggiornandolo `age` alla versione 42.

------
#### [ Async ]

   ```
   Console.WriteLine("Updating the document");
   
   await driver.Execute(async txn =>
   {
       IQuery<Person> myQuery = txn.Query<Person>("UPDATE Person SET Age = ? WHERE FirstName = ?", 42, "John");
       await txn.Execute(myQuery);
   });
   ```

------
#### [ Sync ]

   ```
   Console.WriteLine("Updating the document");
   
   driver.Execute(txn =>
   {
       IQuery<Person> myQuery = txn.Query<Person>("UPDATE Person SET Age = ? WHERE FirstName = ?", 42, "John");
       txn.Execute(myQuery);
   });
   ```

------

1. Interroga nuovamente il documento per vedere il valore aggiornato.

------
#### [ Async ]

   ```
   Console.WriteLine("Querying the table for the updated document");
   
   IAsyncResult<Person> updateResult = await driver.Execute(async txn =>
   {
       IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
       return await txn.Execute(myQuery);
   });
   
   await foreach (Person person in updateResult)
   {
       Console.WriteLine(person);
       // John, Doe, 42
   }
   ```

------
#### [ Sync ]

   ```
   Console.WriteLine("Querying the table for the updated document");
   
   IResult<Person> updateResult = driver.Execute(txn =>
   {
       IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
       return txn.Execute(myQuery);
   });
   
   foreach (Person person in updateResult)
   {
       Console.WriteLine(person);
       // John, Doe, 42
   }
   ```

------

1. Per eseguire l'applicazione, immettete il seguente comando dalla directory principale della directory del `Amazon.QLDB.QuickStartGuide` progetto.

   ```
   $ dotnet run --project Amazon.QLDB.QuickStartGuide
   ```

### Utilizzo della libreria Ion


1. Aggiungi il codice seguente che aggiorna un documento nella `Person` tabella aggiornandolo `age` a 42.

------
#### [ Async ]

   ```
   Console.WriteLine("Updating the document");
   
   IIonValue ionIntAge = valueFactory.NewInt(42);
   IIonValue ionFirstName2 = valueFactory.NewString("John");
   
   await driver.Execute(async txn =>
   {
       await txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2);
   });
   ```

------
#### [ Sync ]

   ```
   Console.WriteLine("Updating a document");
   
   IIonValue ionIntAge = valueFactory.NewInt(42);
   IIonValue ionFirstName2 = valueFactory.NewString("John");
   
   driver.Execute(txn =>
   {
       txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2);
   });
   ```

------

1. Interroga nuovamente il documento per vedere il valore aggiornato.

------
#### [ Async ]

   ```
   Console.WriteLine("Querying the table for the updated document");
   
   IIonValue ionFirstName3 = valueFactory.NewString("John");
   
   IAsyncResult updateResult = await driver.Execute(async txn =>
   {
       return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3 );
   });
   
   await foreach (IIonValue row in updateResult)
   {
       Console.WriteLine(row.GetField("firstName").StringValue);
       Console.WriteLine(row.GetField("lastName").StringValue);
       Console.WriteLine(row.GetField("age").IntValue);
   }
   ```

------
#### [ Sync ]

   ```
   Console.WriteLine("Querying the table for the updated document");
   
   IIonValue ionFirstName3 = valueFactory.NewString("John");
   
   IResult updateResult = driver.Execute(txn =>
   {
       return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3);
   });
   
   foreach (IIonValue row in updateResult)
   {
       Console.WriteLine(row.GetField("firstName").StringValue);
       Console.WriteLine(row.GetField("lastName").StringValue);
       Console.WriteLine(row.GetField("age").IntValue);
   }
   ```

------

1. Per eseguire l'applicazione, immettete il seguente comando dalla directory principale della directory del `Amazon.QLDB.QuickStartGuide` progetto.

   ```
   $ dotnet run --project Amazon.QLDB.QuickStartGuide
   ```

## Esecuzione dell'applicazione completa


Il seguente esempio di codice è la versione completa dell'`Program.cs`applicazione. Invece di eseguire i passaggi precedenti singolarmente, potete anche copiare ed eseguire questo esempio di codice dall'inizio alla fine. Questa applicazione dimostra alcune operazioni CRUD di base sul registro denominato. `quick-start`

**Nota**  
Prima di eseguire questo codice, assicuratevi di non avere già una tabella attiva denominata `Person` nel registro. `quick-start`

------
#### [ Async ]

```
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;

namespace Amazon.QLDB.QuickStartGuide
{
    class Program
    {
        public class Person
        {
            public string FirstName { get; set; }

            public string LastName { get; set; }

            public int Age { get; set; }

            public override string ToString()
            {
                return FirstName + ", " + LastName + ", " + Age.ToString();
            }
        }

        static async Task Main(string[] args)
        {
            Console.WriteLine("Create the async QLDB driver");
            IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
                .WithLedger("quick-start")
                .WithSerializer(new ObjectSerializer())
                .Build();

            Console.WriteLine("Creating the table and index");

            // Creates the table and the index in the same transaction.
            // Note: Any code within the lambda can potentially execute multiple times due to retries.
            // For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
            await driver.Execute(async txn =>
            {
                await txn.Execute("CREATE TABLE Person");
                await txn.Execute("CREATE INDEX ON Person(firstName)");
            });

            Console.WriteLine("Inserting a document");

            Person myPerson = new Person {
                FirstName = "John",
                LastName = "Doe",
                Age = 32
            };

            await driver.Execute(async txn =>
            {
                IQuery<Person> myQuery = txn.Query<Person>("INSERT INTO Person ?", myPerson);
                await txn.Execute(myQuery);
            });

            Console.WriteLine("Querying the table");

            // The result from driver.Execute() is buffered into memory because once the
            // transaction is committed, streaming the result is no longer possible.
            IAsyncResult<Person> selectResult = await driver.Execute(async txn =>
            {
                IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
                return await txn.Execute(myQuery);
            });

            await foreach (Person person in selectResult)
            {
                Console.WriteLine(person);
                // John, Doe, 32
            }

            Console.WriteLine("Updating the document");

            await driver.Execute(async txn =>
            {
                IQuery<Person> myQuery = txn.Query<Person>("UPDATE Person SET Age = ? WHERE FirstName = ?", 42, "John");
                await txn.Execute(myQuery);
            });

            Console.WriteLine("Querying the table for the updated document");

            IAsyncResult<Person> updateResult = await driver.Execute(async txn =>
            {
                IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
                return await txn.Execute(myQuery);
            });

            await foreach (Person person in updateResult)
            {
                Console.WriteLine(person);
                // John, Doe, 42
            }
        }
    }
}
```

------
#### [ Sync ]

```
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;

namespace Amazon.QLDB.QuickStartGuide
{
    class Program
    {
        public class Person
        {
            public string FirstName { get; set; }

            public string LastName { get; set; }

            public int Age { get; set; }

            public override string ToString()
            {
                return FirstName + ", " + LastName + ", " + Age.ToString();
            }
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Create the sync QLDB driver");
            IQldbDriver driver = QldbDriver.Builder()
                .WithLedger("quick-start")
                .WithSerializer(new ObjectSerializer())
                .Build();

            Console.WriteLine("Creating the table and index");

            // Creates the table and the index in the same transaction.
            // Note: Any code within the lambda can potentially execute multiple times due to retries.
            // For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
            driver.Execute(txn =>
            {
                txn.Execute("CREATE TABLE Person");
                txn.Execute("CREATE INDEX ON Person(firstName)");
            });

            Console.WriteLine("Inserting a document");

            Person myPerson = new Person {
                FirstName = "John",
                LastName = "Doe",
                Age = 32
            };

            driver.Execute(txn =>
            {
                IQuery<Person> myQuery = txn.Query<Person>("INSERT INTO Person ?", myPerson);
                txn.Execute(myQuery);
            });

            Console.WriteLine("Querying the table");

            // The result from driver.Execute() is buffered into memory because once the
            // transaction is committed, streaming the result is no longer possible.
            IResult<Person> selectResult = driver.Execute(txn =>
            {
                IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
                return txn.Execute(myQuery);
            });

            foreach (Person person in selectResult)
            {
                Console.WriteLine(person);
                // John, Doe, 32
            }

            Console.WriteLine("Updating the document");

            driver.Execute(txn =>
            {
                IQuery<Person> myQuery = txn.Query<Person>("UPDATE Person SET Age = ? WHERE FirstName = ?", 42, "John");
                txn.Execute(myQuery);
            });

            Console.WriteLine("Querying the table for the updated document");

            IResult<Person> updateResult = driver.Execute(txn =>
            {
                IQuery<Person> myQuery = txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "John");
                return txn.Execute(myQuery);
            });

            foreach (Person person in updateResult)
            {
                Console.WriteLine(person);
                // John, Doe, 42
            }

        }
    }
}
```

------

### Utilizzo della libreria Ion


------
#### [ Async ]

```
using System;
using System.Threading.Tasks;
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;
using Amazon.QLDB.Driver;
using IAsyncResult = Amazon.QLDB.Driver.IAsyncResult;

namespace Amazon.QLDB.QuickStartGuide
{
    class Program
    {
        static IValueFactory valueFactory = new ValueFactory();

        static async Task Main(string[] args)
        {
            Console.WriteLine("Create the async QLDB driver");
            IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
                .WithLedger("quick-start")
                .Build();

            Console.WriteLine("Creating the table and index");

            // Creates the table and the index in the same transaction.
            // Note: Any code within the lambda can potentially execute multiple times due to retries.
            // For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
            await driver.Execute(async txn =>
            {
                await txn.Execute("CREATE TABLE Person");
                await txn.Execute("CREATE INDEX ON Person(firstName)");
            });

            Console.WriteLine("Inserting a document");

            // This is one way of creating Ion values. We can also use an IonLoader.
            // For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion
            IIonValue ionPerson = valueFactory.NewEmptyStruct();
            ionPerson.SetField("firstName", valueFactory.NewString("John"));
            ionPerson.SetField("lastName", valueFactory.NewString("Doe"));
            ionPerson.SetField("age", valueFactory.NewInt(32));

            await driver.Execute(async txn =>
            {
                await txn.Execute("INSERT INTO Person ?", ionPerson);
            });

            Console.WriteLine("Querying the table");

            IIonValue ionFirstName = valueFactory.NewString("John");

            // The result from driver.Execute() is buffered into memory because once the
            // transaction is committed, streaming the result is no longer possible.
            IAsyncResult selectResult = await driver.Execute(async txn =>
            {
                return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName);
            });

            await foreach (IIonValue row in selectResult)
            {
                Console.WriteLine(row.GetField("firstName").StringValue);
                Console.WriteLine(row.GetField("lastName").StringValue);
                Console.WriteLine(row.GetField("age").IntValue);
            }

            Console.WriteLine("Updating the document");

            IIonValue ionIntAge = valueFactory.NewInt(42);
            IIonValue ionFirstName2 = valueFactory.NewString("John");

            await driver.Execute(async txn =>
            {
                await txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2);
            });

            Console.WriteLine("Querying the table for the updated document");

            IIonValue ionFirstName3 = valueFactory.NewString("John");

            IAsyncResult updateResult = await driver.Execute(async txn =>
            {
                return await txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3);
            });

            await foreach (IIonValue row in updateResult)
            {
                Console.WriteLine(row.GetField("firstName").StringValue);
                Console.WriteLine(row.GetField("lastName").StringValue);
                Console.WriteLine(row.GetField("age").IntValue);
            }
        }
    }
}
```

------
#### [ Sync ]

```
using System;
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;
using Amazon.QLDB.Driver;

namespace Amazon.QLDB.QuickStartGuide
{
    class Program
    {
        static IValueFactory valueFactory = new ValueFactory();

        static void Main(string[] args)
        {
            Console.WriteLine("Create the sync QLDB Driver");
            IQldbDriver driver = QldbDriver.Builder()
                .WithLedger("quick-start")
                .Build();

            Console.WriteLine("Creating the tables and index");

            // Creates the table and the index in the same transaction.
            // Note: Any code within the lambda can potentially execute multiple times due to retries.
            // For more information, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-retry-policy
            driver.Execute(txn =>
            {
                txn.Execute("CREATE TABLE Person");
                txn.Execute("CREATE INDEX ON Person(firstName)");
            });

            Console.WriteLine("Inserting a document");

            // This is one way of creating Ion values. We can also use an IonLoader.
            // For more details, see: https://docs.aws.amazon.com/qldb/latest/developerguide/driver-cookbook-dotnet.html#cookbook-dotnet.ion
            IIonValue ionPerson = valueFactory.NewEmptyStruct();
            ionPerson.SetField("firstName", valueFactory.NewString("John"));
            ionPerson.SetField("lastName", valueFactory.NewString("Doe"));
            ionPerson.SetField("age", valueFactory.NewInt(32));

            driver.Execute(txn =>
            {
                txn.Execute("INSERT INTO Person ?", ionPerson);
            });

            Console.WriteLine("Querying the table");

            IIonValue ionFirstName = valueFactory.NewString("John");

            // The result from driver.Execute() is buffered into memory because once the
            // transaction is committed, streaming the result is no longer possible.
            IResult selectResult = driver.Execute(txn =>
            {
                return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName);
            });

            foreach (IIonValue row in selectResult)
            {
                Console.WriteLine(row.GetField("firstName").StringValue);
                Console.WriteLine(row.GetField("lastName").StringValue);
                Console.WriteLine(row.GetField("age").IntValue);
            }

            Console.WriteLine("Updating a document");

            IIonValue ionIntAge = valueFactory.NewInt(42);
            IIonValue ionFirstName2 = valueFactory.NewString("John");

            driver.Execute(txn =>
            {
                txn.Execute("UPDATE Person SET age = ? WHERE firstName = ?", ionIntAge, ionFirstName2);
            });

            Console.WriteLine("Querying the table for the updated document");

            IIonValue ionFirstName3 = valueFactory.NewString("John");

            IResult updateResult = driver.Execute(txn =>
            {
                return txn.Execute("SELECT * FROM Person WHERE firstName = ?", ionFirstName3);
            });

            foreach (IIonValue row in updateResult)
            {
                Console.WriteLine(row.GetField("firstName").StringValue);
                Console.WriteLine(row.GetField("lastName").StringValue);
                Console.WriteLine(row.GetField("age").IntValue);
            }
        }
    }
}
```

------

Per eseguire l'applicazione completa, immettete il seguente comando dalla directory principale della directory del `Amazon.QLDB.QuickStartGuide` progetto.

```
$ dotnet run --project Amazon.QLDB.QuickStartGuide
```

# Driver Amazon QLDB per.NET — Guida di riferimento al libro di cucina
Riferimento al libro di cucina

**Importante**  
Avviso di fine del supporto: i clienti esistenti potranno utilizzare Amazon QLDB fino alla fine del supporto, il 31/07/2025. Per ulteriori dettagli, consulta [Migrare un registro Amazon QLDB su Amazon Aurora PostgreSQL](https://aws.amazon.com/blogs/database/migrate-an-amazon-qldb-ledger-to-amazon-aurora-postgresql/).

Questa guida di riferimento mostra i casi d'uso comuni del driver Amazon QLDB per.NET. Fornisce esempi di codice C\$1 che dimostrano come utilizzare il driver per eseguire operazioni di base di *creazione, lettura, aggiornamento ed eliminazione* (CRUD). Include anche esempi di codice per l'elaborazione dei dati di Amazon Ion. Inoltre, questa guida illustra le migliori pratiche per rendere le transazioni idempotenti e implementare vincoli di unicità.

**Nota**  
Questo argomento fornisce esempi di codice per l'elaborazione di dati Amazon Ion utilizzando lo strumento di [mappatura di oggetti Ion per](https://github.com/amzn/ion-object-mapper-dotnet) impostazione predefinita. QLDB ha introdotto lo Ion object Mapper nella versione 1.3.0 del driver.NET. Ove applicabile, questo argomento fornisce anche esempi di codice che utilizzano la [libreria Ion](https://github.com/amzn/ion-dotnet) standard come alternativa. Per ulteriori informazioni, consulta [Lavorare con Amazon Ion](#cookbook-dotnet.ion).

**Contents**
+ [

## Importazione del driver
](#cookbook-dotnet.importing)
+ [

## Istanziazione del driver
](#cookbook-dotnet.instantiating)
+ [

## Operazioni CRUD
](#cookbook-dotnet.crud)
  + [

### Creazione di tabelle
](#cookbook-dotnet.crud.creating-tables)
  + [

### Creazione di indici
](#cookbook-dotnet.crud.creating-indexes)
  + [

### Leggere documenti
](#cookbook-dotnet.crud.reading)
    + [

#### Utilizzo dei parametri di interrogazione
](#cookbook-dotnet.reading-using-params)
  + [

### Inserimento di documenti
](#cookbook-dotnet.crud.inserting)
    + [

#### Inserimento di più documenti in un'unica dichiarazione
](#cookbook-dotnet.crud.inserting.multiple)
  + [

### Aggiornamento dei documenti
](#cookbook-dotnet.crud.updating)
  + [

### Eliminazione di documenti
](#cookbook-dotnet.crud.deleting)
  + [

### Esecuzione di più istruzioni in una transazione
](#cookbook-dotnet.crud.multi-statement)
  + [

### Logica di ripetizione dei tentativi
](#cookbook-dotnet.crud.retry-logic)
  + [

### Implementazione di vincoli di unicità
](#cookbook-dotnet.crud.uniqueness-constraints)
+ [

## Lavorare con Amazon Ion
](#cookbook-dotnet.ion)
  + [

### Importazione del modulo Ion
](#cookbook-dotnet.ion.import)
  + [

### Creazione di tipi di ioni
](#cookbook-dotnet.ion.creating-types)
  + [

### Ottenere un dump binario Ion
](#cookbook-dotnet.ion.getting-binary)
  + [

### Ottenere un dump di testo Ion
](#cookbook-dotnet.ion.getting-text)

## Importazione del driver


Il seguente esempio di codice importa il driver.

```
using Amazon.QLDB.Driver;
using Amazon.QLDB.Driver.Generic;
using Amazon.QLDB.Driver.Serialization;
```

### Utilizzo della libreria Ion


```
using Amazon.QLDB.Driver;
using Amazon.IonDotnet.Builders;
```

## Istanziazione del driver


Il seguente esempio di codice crea un'istanza del driver che si connette a un nome di registro specificato utilizzando le impostazioni predefinite.

------
#### [ Async ]

```
IAsyncQldbDriver driver = AsyncQldbDriver.Builder()
    .WithLedger("vehicle-registration")
    // Add Serialization library
    .WithSerializer(new ObjectSerializer())
    .Build();
```

------
#### [ Sync ]

```
IQldbDriver driver = QldbDriver.Builder()
    .WithLedger("vehicle-registration")
    // Add Serialization library
    .WithSerializer(new ObjectSerializer())
    .Build();
```

------

### Utilizzo della libreria Ion


------
#### [ Async ]

```
IAsyncQldbDriver driver = AsyncQldbDriver.Builder().WithLedger("vehicle-registration").Build();
```

------
#### [ Sync ]

```
IQldbDriver driver = QldbDriver.Builder().WithLedger("vehicle-registration").Build();
```

------

## Operazioni CRUD


QLDB *esegue operazioni di creazione, lettura, aggiornamento ed* eliminazione (CRUD) come parte di una transazione.

**avvertimento**  
Come best practice, rendi le tue transazioni di scrittura strettamente idempotenti.

**Rendere le transazioni idempotenti**

Si consiglia di rendere le transazioni di scrittura idempotenti per evitare effetti collaterali imprevisti in caso di nuovi tentativi. Una transazione è *idempotente* se può essere eseguita più volte e produrre risultati identici ogni volta.

Ad esempio, si consideri una transazione che inserisce un documento in una tabella denominata. `Person` La transazione deve innanzitutto verificare se il documento esiste già o meno nella tabella. Senza questo controllo, la tabella potrebbe finire con documenti duplicati.

Supponiamo che QLDB esegua correttamente il commit della transazione sul lato server, ma che il client scada in attesa di una risposta. Se la transazione non è idempotente, lo stesso documento potrebbe essere inserito più di una volta in caso di nuovo tentativo.

**Utilizzo degli indici per evitare scansioni complete della tabella**

Si consiglia inoltre di eseguire istruzioni con una clausola di `WHERE` predicato utilizzando un operatore di *uguaglianza* su un campo indicizzato o un ID di documento, ad esempio o. `WHERE indexedField = 123` `WHERE indexedField IN (456, 789)` *Senza questa ricerca indicizzata, QLDB deve eseguire una scansione della tabella, che può portare a timeout delle transazioni o conflitti ottimistici di controllo della concorrenza (OCC).*

[Modello di concorrenza Amazon QLDB](concurrency.md)Per ulteriori informazioni su OCC, vedere.

**Transazioni create implicitamente**

Il driver [Amazon.QLDB.Driver. ](https://amazon-qldb-docs.s3.amazonaws.com/drivers/dotnet/1.4.1/api/Amazon.QLDB.Driver.IQldbDriver.html)IQldb[Il metodo Driver.Execute accetta una funzione lambda che riceve un'istanza di Amazon.qldb.Driver. TransactionExecutor](https://amazon-qldb-docs.s3.amazonaws.com/drivers/dotnet/1.4.1/api/Amazon.QLDB.Driver.TransactionExecutor.html), che è possibile utilizzare per eseguire le istruzioni. L'istanza di `TransactionExecutor` wraps una transazione creata implicitamente.

È possibile eseguire istruzioni all'interno della funzione lambda utilizzando il `Execute` metodo dell'esecutore della transazione. Il driver esegue implicitamente la transazione quando ritorna la funzione lambda.

Le sezioni seguenti mostrano come eseguire operazioni CRUD di base, specificare una logica di ripetizione personalizzata e implementare vincoli di unicità.

**Contents**
+ [

### Creazione di tabelle
](#cookbook-dotnet.crud.creating-tables)
+ [

### Creazione di indici
](#cookbook-dotnet.crud.creating-indexes)
+ [

### Leggere documenti
](#cookbook-dotnet.crud.reading)
  + [

#### Utilizzo dei parametri di interrogazione
](#cookbook-dotnet.reading-using-params)
+ [

### Inserimento di documenti
](#cookbook-dotnet.crud.inserting)
  + [

#### Inserimento di più documenti in un'unica dichiarazione
](#cookbook-dotnet.crud.inserting.multiple)
+ [

### Aggiornamento dei documenti
](#cookbook-dotnet.crud.updating)
+ [

### Eliminazione di documenti
](#cookbook-dotnet.crud.deleting)
+ [

### Esecuzione di più istruzioni in una transazione
](#cookbook-dotnet.crud.multi-statement)
+ [

### Logica di ripetizione dei tentativi
](#cookbook-dotnet.crud.retry-logic)
+ [

### Implementazione di vincoli di unicità
](#cookbook-dotnet.crud.uniqueness-constraints)

### Creazione di tabelle


------
#### [ Async ]

```
IAsyncResult<Table> createResult = await driver.Execute(async txn =>
{
    IQuery<Table> query = txn.Query<Table>("CREATE TABLE Person");
    return await txn.Execute(query);
});

await foreach (var result in createResult)
{
    Console.WriteLine("{ tableId: " + result.TableId + " }");
    // The statement returns the created table ID:
    // { tableId: 4o5Uk09OcjC6PpJpLahceE }
}
```

------
#### [ Sync ]

```
IResult<Table> createResult = driver.Execute( txn =>
{
    IQuery<Table> query = txn.Query<Table>("CREATE TABLE Person");
    return txn.Execute(query);
});

foreach (var result in createResult)
{
    Console.WriteLine("{ tableId: " + result.TableId + " }");
    // The statement returns the created table ID:
    // { tableId: 4o5Uk09OcjC6PpJpLahceE }
}
```

------

#### Utilizzo della libreria Ion


------
#### [ Async ]

```
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("CREATE TABLE Person");
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the created table ID:
    // {
    //    tableId: "4o5Uk09OcjC6PpJpLahceE"
    // }
}
```

------
#### [ Sync ]

```
// The result from driver.Execute() is buffered into memory because once the
// transaction is committed, streaming the result is no longer possible.
IResult result = driver.Execute(txn =>
{
    return txn.Execute("CREATE TABLE Person");
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the created table ID:
    // {
    //    tableId: "4o5Uk09OcjC6PpJpLahceE"
    // }
}
```

------

### Creazione di indici


------
#### [ Async ]

```
IAsyncResult<Table> createResult = await driver.Execute(async txn =>
{
    IQuery<Table> query = txn.Query<Table>("CREATE INDEX ON Person(firstName)");
    return await txn.Execute(query);
});

await foreach (var result in createResult)
{
    Console.WriteLine("{ tableId: " + result.TableId + " }");
    // The statement returns the updated table ID:
    // { tableId: 4o5Uk09OcjC6PpJpLahceE }
}
```

------
#### [ Sync ]

```
IResult<Table> createResult = driver.Execute(txn =>
{
    IQuery<Table> query = txn.Query<Table>("CREATE INDEX ON Person(firstName)");
    return txn.Execute(query);
});

foreach (var result in createResult)
{
    Console.WriteLine("{ tableId: " + result.TableId + " }");
    // The statement returns the updated table ID:
    // { tableId: 4o5Uk09OcjC6PpJpLahceE }
}
```

------

#### Utilizzo della libreria Ion


------
#### [ Async ]

```
IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("CREATE INDEX ON Person(GovId)");
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the updated table ID:
    // {
    //    tableId: "4o5Uk09OcjC6PpJpLahceE"
    // }
}
```

------
#### [ Sync ]

```
IResult result = driver.Execute(txn =>
{
    return txn.Execute("CREATE INDEX ON Person(GovId)");
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the updated table ID:
    // {
    //    tableId: "4o5Uk09OcjC6PpJpLahceE"
    // }
}
```

------

### Leggere documenti


```
// Assumes that Person table has documents as follows:
// { "GovId": "TOYENC486FH", "FirstName" : "Brent" }
// Person class is defined as follows:
// public class Person
// {
//     public string GovId { get; set; }
//     public string FirstName { get; set; }
//  }

IAsyncResult<Person> result = await driver.Execute(async txn =>
{
    return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId = 'TOYENC486FH'"));
});

await foreach (Person person in result)
{
    Console.WriteLine(person.GovId); // Prints TOYENC486FH.
    Console.WriteLine(person.FirstName); // Prints Brent.
}
```

**Nota**  
Quando si esegue una query senza una ricerca indicizzata, viene richiamata una scansione completa della tabella. In questo esempio, si consiglia di disporre di un [indice](ql-reference.create-index.md) sul campo per ottimizzare le `GovId` prestazioni. Senza un indice attivo`GovId`, le query possono avere una maggiore latenza e possono anche portare a eccezioni nei conflitti OCC o a timeout delle transazioni.

#### Utilizzo dei parametri di interrogazione


Il seguente esempio di codice utilizza un parametro di query di tipo C\$1.

```
IAsyncResult<Person> result = await driver.Execute(async txn =>
{
    return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE FirstName = ?", "Brent"));
});

await foreach (Person person in result)
{
    Console.WriteLine(person.GovId); // Prints TOYENC486FH.
    Console.WriteLine(person.FirstName); // Prints Brent.
}
```

Il seguente esempio di codice utilizza più parametri di query di tipo C\$1.

```
IAsyncResult<Person> result = await driver.Execute(async txn =>
{
    return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId = ? AND FirstName = ?", "TOYENC486FH", "Brent"));
});

await foreach (Person person in result)
{
    Console.WriteLine(person.GovId); // Prints TOYENC486FH.
    Console.WriteLine(person.FirstName); // Prints Brent.
}
```

Il seguente esempio di codice utilizza una matrice di parametri di query di tipo C\$1.

```
// Assumes that Person table has documents as follows:
// { "GovId": "TOYENC486FH", "FirstName" : "Brent" }
// { "GovId": "ROEE1C1AABH", "FirstName" : "Jim" }
// { "GovId": "YH844DA7LDB", "FirstName" : "Mary" }

string[] ids = {
    "TOYENC486FH",
    "ROEE1C1AABH",
    "YH844DA7LDB"
};

IAsyncResult<Person> result = await driver.Execute(async txn =>
{
    return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId IN (?,?,?)", ids));
});

await foreach (Person person in result)
{
    Console.WriteLine(person.FirstName); // Prints Brent on first iteration.
    // Prints Jim on second iteration.
    // Prints Mary on third iteration.
}
```

Il seguente esempio di codice utilizza un elenco C\$1 come valore.

```
// Assumes that Person table has document as follows:
// { "GovId": "TOYENC486FH",
//   "FirstName" : "Brent",
//   "Vehicles": [
//      { "Make": "Volkswagen",
//        "Model": "Golf"},
//      { "Make": "Honda",
//        "Model": "Civic"}
//   ]
// }
// Person class is defined as follows:
// public class Person
// {
//     public string GovId { get; set; }
//     public string FirstName { get; set; }
//     public List<Vehicle> Vehicles { get; set; }
// }
// Vehicle class is defined as follows:
// public class Vehicle
// {
//     public string Make { get; set; }
//     public string Model { get; set; }
// }

List<Vehicle> vehicles = new List<Vehicle>
{
    new Vehicle
    {
        Make = "Volkswagen",
        Model = "Golf"
    },
    new Vehicle
    {
        Make = "Honda",
        Model = "Civic"
    }
};

IAsyncResult<Person> result = await driver.Execute(async txn =>
{
    return await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE Vehicles = ?", vehicles));
});

await foreach (Person person in result)
{
    Console.WriteLine("{");
    Console.WriteLine($"  GovId: {person.GovId},");
    Console.WriteLine($"  FirstName: {person.FirstName},");
    Console.WriteLine("  Vehicles: [");
    foreach (Vehicle vehicle in person.Vehicles)
    {
        Console.WriteLine("  {");
        Console.WriteLine($"    Make: {vehicle.Make},");
        Console.WriteLine($"    Model: {vehicle.Model},");
        Console.WriteLine("  },");
    }
    Console.WriteLine("  ]");
    Console.WriteLine("}");
    // Prints:
    // {
    //     GovId: TOYENC486FH,
    //     FirstName: Brent,
    //     Vehicles: [
    //     {
    //         Make: Volkswagen,
    //         Model: Golf
    //     },
    //     {
    //         Make: Honda,
    //         Model: Civic
    //     },
    //     ]
    // }
}
```

#### Utilizzo della libreria Ion


------
#### [ Async ]

```
// Assumes that Person table has documents as follows:
// { "GovId": "TOYENC486FH", "FirstName" : "Brent" }

IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("SELECT * FROM Person WHERE GovId = 'TOYENC486FH'");
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH.
    Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent.
}
```

------
#### [ Sync ]

```
// Assumes that Person table has documents as follows:
// { "GovId": "TOYENC486FH", "FirstName" : "Brent" }

IResult result = driver.Execute(txn =>
{
    return txn.Execute("SELECT * FROM Person WHERE GovId = 'TOYENC486FH'");
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH.
    Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent.
}
```

------

**Nota**  
Quando si esegue una query senza una ricerca indicizzata, viene richiamata una scansione completa della tabella. In questo esempio, si consiglia di disporre di un [indice](ql-reference.create-index.md) sul campo per ottimizzare le `GovId` prestazioni. Senza un indice attivo`GovId`, le query possono avere una maggiore latenza e possono anche portare a eccezioni nei conflitti OCC o a timeout delle transazioni.

Il seguente esempio di codice utilizza un parametro di query di tipo Ion.

------
#### [ Async ]

```
IValueFactory valueFactory = new ValueFactory();
IIonValue ionFirstName = valueFactory.NewString("Brent");

IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("SELECT * FROM Person WHERE FirstName = ?", ionFirstName);
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH.
    Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent.
}
```

------
#### [ Sync ]

```
IValueFactory valueFactory = new ValueFactory();
IIonValue ionFirstName = valueFactory.NewString("Brent");

IResult result = driver.Execute(txn =>
{
    return txn.Execute("SELECT * FROM Person WHERE FirstName = ?", ionFirstName);
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH.
    Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent.
}
```

------

Il seguente esempio di codice utilizza più parametri di query.

------
#### [ Async ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");
IIonValue ionFirstName = valueFactory.NewString("Brent");

IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("SELECT * FROM Person WHERE GovId = ? AND FirstName = ?", ionGovId, ionFirstName);
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH.
    Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent.
}
```

------
#### [ Sync ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");
IIonValue ionFirstName = valueFactory.NewString("Brent");

IResult result = driver.Execute(txn =>
{
    return txn.Execute("SELECT * FROM Person WHERE GovId = ? AND FirstName = ?", ionGovId, ionFirstName);
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.GetField("GovId").StringValue); // Prints TOYENC486FH.
    Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent.
}
```

------

Il seguente esempio di codice utilizza un elenco di parametri di query.

------
#### [ Async ]

```
// Assumes that Person table has documents as follows:
// { "GovId": "TOYENC486FH", "FirstName" : "Brent" }
// { "GovId": "ROEE1C1AABH", "FirstName" : "Jim" }
// { "GovId": "YH844DA7LDB", "FirstName" : "Mary" }

IIonValue[] ionIds = {
    valueFactory.NewString("TOYENC486FH"),
    valueFactory.NewString("ROEE1C1AABH"),
    valueFactory.NewString("YH844DA7LDB")
};

IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("SELECT * FROM Person WHERE GovId IN (?,?,?)", ionIds);
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent on first iteration.
                                                              // Prints Jim on second iteration.
                                                              // Prints Mary on third iteration.
}
```

------
#### [ Sync ]

```
// Assumes that Person table has documents as follows:
// { "GovId": "TOYENC486FH", "FirstName" : "Brent" }
// { "GovId": "ROEE1C1AABH", "FirstName" : "Jim" }
// { "GovId": "YH844DA7LDB", "FirstName" : "Mary" }

IIonValue[] ionIds = {
    valueFactory.NewString("TOYENC486FH"),
    valueFactory.NewString("ROEE1C1AABH"),
    valueFactory.NewString("YH844DA7LDB")
};

IResult result = driver.Execute(txn =>
{
    return txn.Execute("SELECT * FROM Person WHERE GovId IN (?,?,?)", ionIds);
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.GetField("FirstName").StringValue); // Prints Brent on first iteration.
                                                              // Prints Jim on second iteration.
                                                              // Prints Mary on third iteration.
}
```

------

Il seguente esempio di codice utilizza un elenco di ioni come valore. Per ulteriori informazioni sull'utilizzo di diversi tipi di ioni, vedere[Utilizzo dei tipi di dati Amazon Ion in Amazon QLDB](driver-working-with-ion.md).

------
#### [ Async ]

```
// Assumes that Person table has document as follows:
// { "GovId": "TOYENC486FH",
//   "FirstName" : "Brent",
//   "Vehicles": [
//      { "Make": "Volkswagen",
//        "Model": "Golf"},
//      { "Make": "Honda",
//        "Model": "Civic"}
//   ]
// }

IIonValue ionVehicle1 = valueFactory.NewEmptyStruct();
ionVehicle1.SetField("Make", valueFactory.NewString("Volkswagen"));
ionVehicle1.SetField("Model", valueFactory.NewString("Golf"));

IIonValue ionVehicle2 = valueFactory.NewEmptyStruct();
ionVehicle2.SetField("Make", valueFactory.NewString("Honda"));
ionVehicle2.SetField("Model", valueFactory.NewString("Civic"));

IIonValue ionVehicles =  valueFactory.NewEmptyList();
ionVehicles.Add(ionVehicle1);
ionVehicles.Add(ionVehicle2);

IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("SELECT * FROM Person WHERE Vehicles = ?", ionVehicles);
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // Prints:
    // {
    //     GovId: "TOYENC486FN",
    //     FirstName: "Brent",
    //     Vehicles: [
    //     {
    //         Make: "Volkswagen",
    //         Model: "Golf"
    //     },
    //     {
    //         Make: "Honda",
    //         Model: "Civic"
    //     }
    //     ]
    // }
}
```

------
#### [ Sync ]

```
// Assumes that Person table has document as follows:
// { "GovId": "TOYENC486FH",
//   "FirstName" : "Brent",
//   "Vehicles": [
//      { "Make": "Volkswagen",
//        "Model": "Golf"},
//      { "Make": "Honda",
//        "Model": "Civic"}
//   ]
// }

IIonValue ionVehicle1 = valueFactory.NewEmptyStruct();
ionVehicle1.SetField("Make", valueFactory.NewString("Volkswagen"));
ionVehicle1.SetField("Model", valueFactory.NewString("Golf"));

IIonValue ionVehicle2 = valueFactory.NewEmptyStruct();
ionVehicle2.SetField("Make", valueFactory.NewString("Honda"));
ionVehicle2.SetField("Model", valueFactory.NewString("Civic"));

IIonValue ionVehicles =  valueFactory.NewEmptyList();
ionVehicles.Add(ionVehicle1);
ionVehicles.Add(ionVehicle2);

IResult result = driver.Execute(txn =>
{
    return txn.Execute("SELECT * FROM Person WHERE Vehicles = ?", ionVehicles);
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // Prints:
    // {
    //     GovId: "TOYENC486FN",
    //     FirstName: "Brent",
    //     Vehicles: [
    //     {
    //         Make: "Volkswagen",
    //         Model: "Golf"
    //     },
    //     {
    //         Make: "Honda",
    //         Model: "Civic"
    //     }
    //     ]
    // }
}
```

------

### Inserimento di documenti


Il seguente esempio di codice inserisce i tipi di dati Ion.

```
string govId = "TOYENC486FH";

Person person = new Person
{
    GovId = "TOYENC486FH",
    FirstName = "Brent"
};

await driver.Execute(async txn =>
{
    // Check if a document with GovId:TOYENC486FH exists
    // This is critical to make this transaction idempotent
    IAsyncResult<Person> result = await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId = ?", govId));

    // Check if there is a record in the cursor.
    int count = await result.CountAsync();
    if (count > 0)
    {
        // Document already exists, no need to insert
        return;
    }

    // Insert the document.
    await txn.Execute(txn.Query<Document>("INSERT INTO Person ?", person));
});
```

#### Utilizzo della libreria Ion


------
#### [ Async ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");

IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("GovId", valueFactory.NewString("TOYENC486FH"));
ionPerson.SetField("FirstName", valueFactory.NewString("Brent"));

await driver.Execute(async txn =>
{
    // Check if a document with GovId:TOYENC486FH exists
    // This is critical to make this transaction idempotent
    IAsyncResult result = await txn.Execute("SELECT * FROM Person WHERE GovId = ?", ionGovId);

    // Check if there is a record in the cursor.
    int count = await result.CountAsync();
    if (count > 0)
    {
        // Document already exists, no need to insert
        return;
    }

    // Insert the document.
    await txn.Execute("INSERT INTO Person ?", ionPerson);
});
```

------
#### [ Sync ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");

IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("GovId", valueFactory.NewString("TOYENC486FH"));
ionPerson.SetField("FirstName", valueFactory.NewString("Brent"));

driver.Execute(txn =>
{
    // Check if a document with GovId:TOYENC486FH exists
    // This is critical to make this transaction idempotent
    IResult result = txn.Execute("SELECT * FROM Person WHERE GovId = ?", ionGovId);

    // Check if there is a record in the cursor.
    int count = result.Count();
    if (count > 0)
    {
        // Document already exists, no need to insert
        return;
    }

    // Insert the document.
    txn.Execute("INSERT INTO Person ?", ionPerson);
});
```

------

Questa transazione inserisce un documento nella `Person` tabella. Prima dell'inserimento, controlla innanzitutto se il documento esiste già nella tabella. **Questo controllo rende la transazione di natura idempotente.** Anche se esegui questa transazione più volte, non causerà effetti collaterali indesiderati.

**Nota**  
In questo esempio, consigliamo di avere un indice sul `GovId` campo per ottimizzare le prestazioni. Senza un indice attivo`GovId`, le istruzioni possono avere una maggiore latenza e possono anche portare a eccezioni nei conflitti OCC o a timeout delle transazioni.

#### Inserimento di più documenti in un'unica dichiarazione


Per inserire più documenti utilizzando un'unica [INSERT](ql-reference.insert.md) istruzione, è possibile passare un `List` parametro C\$1 all'istruzione nel modo seguente.

```
Person person1 = new Person
{
    FirstName = "Brent",
    GovId = "TOYENC486FH"
};

Person person2 = new Person
{
    FirstName = "Jim",
    GovId = "ROEE1C1AABH"
};

List<Person> people = new List<Person>();
people.Add(person1);
people.Add(person2);

IAsyncResult<Document> result = await driver.Execute(async txn =>
{
    return await txn.Execute(txn.Query<Document>("INSERT INTO Person ?", people));
});

await foreach (Document row in result)
{
    Console.WriteLine("{ documentId: " + row.DocumentId + " }");
    // The statement returns the created documents' ID:
    // { documentId: 6BFt5eJQDFLBW2aR8LPw42 }
    // { documentId: K5Zrcb6N3gmIEHgGhwoyKF }
}
```

##### Utilizzo della libreria Ion


Per inserire più documenti utilizzando una singola [INSERT](ql-reference.insert.md) istruzione, è possibile passare un parametro di tipo [Ion list](driver-working-with-ion.md#driver-ion-list) all'istruzione come segue.

------
#### [ Async ]

```
IIonValue ionPerson1 = valueFactory.NewEmptyStruct();
ionPerson1.SetField("FirstName", valueFactory.NewString("Brent"));
ionPerson1.SetField("GovId", valueFactory.NewString("TOYENC486FH"));

IIonValue ionPerson2 = valueFactory.NewEmptyStruct();
ionPerson2.SetField("FirstName", valueFactory.NewString("Jim"));
ionPerson2.SetField("GovId", valueFactory.NewString("ROEE1C1AABH"));

IIonValue ionPeople = valueFactory.NewEmptyList();
ionPeople.Add(ionPerson1);
ionPeople.Add(ionPerson2);

IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("INSERT INTO Person ?", ionPeople);
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the created documents' ID:
    // {
    //     documentId: "6BFt5eJQDFLBW2aR8LPw42"
    // }
    //
    // {
    //     documentId: "K5Zrcb6N3gmIEHgGhwoyKF"
    // }
}
```

------
#### [ Sync ]

```
IIonValue ionPerson1 = valueFactory.NewEmptyStruct();
ionPerson1.SetField("FirstName", valueFactory.NewString("Brent"));
ionPerson1.SetField("GovId", valueFactory.NewString("TOYENC486FH"));

IIonValue ionPerson2 = valueFactory.NewEmptyStruct();
ionPerson2.SetField("FirstName", valueFactory.NewString("Jim"));
ionPerson2.SetField("GovId", valueFactory.NewString("ROEE1C1AABH"));

IIonValue ionPeople = valueFactory.NewEmptyList();
ionPeople.Add(ionPerson1);
ionPeople.Add(ionPerson2);

IResult result = driver.Execute(txn =>
{
    return txn.Execute("INSERT INTO Person ?", ionPeople);
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the created documents' ID:
    // {
    //     documentId: "6BFt5eJQDFLBW2aR8LPw42"
    // }
    //
    // {
    //     documentId: "K5Zrcb6N3gmIEHgGhwoyKF"
    // }
}
```

------

Non racchiudete la variabile placeholder (`?`) tra parentesi angolari doppie (`<<...>>`) quando passate un elenco di ioni. *Nelle istruzioni PartiQL manuali, le parentesi doppie angolari indicano una raccolta non ordinata nota come borsa.*

### Aggiornamento dei documenti


```
string govId = "TOYENC486FH";
string firstName = "John";

IAsyncResult<Document> result = await driver.Execute(async txn =>
{
    return await txn.Execute(txn.Query<Document>("UPDATE Person SET FirstName = ? WHERE GovId = ?", firstName , govId));
});

await foreach (Document row in result)
{
    Console.WriteLine("{ documentId: " + row.DocumentId + " }");
    // The statement returns the updated document ID:
    // { documentId: Djg30Zoltqy5M4BFsA2jSJ }
}
```

#### Utilizzo della libreria Ion


------
#### [ Async ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");
IIonValue ionFirstName = valueFactory.NewString("John");

IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("UPDATE Person SET FirstName = ? WHERE GovId = ?", ionFirstName , ionGovId);
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the updated document ID:
    // {
    //     documentId: "Djg30Zoltqy5M4BFsA2jSJ"
    // }
}
```

------
#### [ Sync ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");
IIonValue ionFirstName = valueFactory.NewString("John");

IResult result = driver.Execute(txn =>
{
    return txn.Execute("UPDATE Person SET FirstName = ? WHERE GovId = ?", ionFirstName , ionGovId);
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the updated document ID:
    // {
    //     documentId: "Djg30Zoltqy5M4BFsA2jSJ"
    // }
}
```

------

**Nota**  
In questo esempio, consigliamo di avere un indice sul `GovId` campo per ottimizzare le prestazioni. Senza un indice attivo`GovId`, le istruzioni possono avere una maggiore latenza e possono anche portare a eccezioni nei conflitti OCC o a timeout delle transazioni.

### Eliminazione di documenti


```
string govId = "TOYENC486FH";

IAsyncResult<Document> result = await driver.Execute(async txn =>
{
    return await txn.Execute(txn.Query<Document>("DELETE FROM Person WHERE GovId = ?", govId));
});

await foreach (Document row in result)
{
    Console.WriteLine("{ documentId: " + row.DocumentId + " }");
    // The statement returns the updated document ID:
    // { documentId: Djg30Zoltqy5M4BFsA2jSJ }
}
```

#### Utilizzo della libreria Ion


------
#### [ Async ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");

IAsyncResult result = await driver.Execute(async txn =>
{
    return await txn.Execute("DELETE FROM Person WHERE GovId = ?", ionGovId);
});

await foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the deleted document ID:
    // {
    //     documentId: "Djg30Zoltqy5M4BFsA2jSJ"
    // }
}
```

------
#### [ Sync ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");

IResult result = driver.Execute(txn =>
{
    return txn.Execute("DELETE FROM Person WHERE GovId = ?", ionGovId);
});

foreach (IIonValue row in result)
{
    Console.WriteLine(row.ToPrettyString());
    // The statement returns the deleted document ID:
    // {
    //     documentId: "Djg30Zoltqy5M4BFsA2jSJ"
    // }
}
```

------

**Nota**  
In questo esempio, consigliamo di avere un indice sul `GovId` campo per ottimizzare le prestazioni. Senza un indice attivo`GovId`, le istruzioni possono avere una maggiore latenza e possono anche portare a eccezioni nei conflitti OCC o a timeout delle transazioni.

### Esecuzione di più istruzioni in una transazione


```
// This code snippet is intentionally trivial. In reality you wouldn't do this because you'd
// set your UPDATE to filter on vin and insured, and check if you updated something or not.
public static async Task<bool> InsureVehicle(IAsyncQldbDriver driver, string vin)
{
    return await driver.Execute(async txn =>
    {
        // Check if the vehicle is insured.
        Amazon.QLDB.Driver.Generic.IAsyncResult<Vehicle> result = await txn.Execute(
            txn.Query<Vehicle>("SELECT insured FROM Vehicles WHERE vin = ? AND insured = FALSE", vin));

        if (await result.CountAsync() > 0)
        {
            // If the vehicle is not insured, insure it.
            await txn.Execute(
                txn.Query<Document>("UPDATE Vehicles SET insured = TRUE WHERE vin = ?", vin));
            return true;
        }
        return false;
    });
}
```

#### Utilizzo della libreria Ion


------
#### [ Async ]

```
// This code snippet is intentionally trivial. In reality you wouldn't do this because you'd
// set your UPDATE to filter on vin and insured, and check if you updated something or not.
public static async Task<bool> InsureVehicle(IAsyncQldbDriver driver, string vin)
{
    ValueFactory valueFactory = new ValueFactory();
    IIonValue ionVin = valueFactory.NewString(vin);

    return await driver.Execute(async txn =>
    {
        // Check if the vehicle is insured.
        Amazon.QLDB.Driver.IAsyncResult result = await txn.Execute(
            "SELECT insured FROM Vehicles WHERE vin = ? AND insured = FALSE", ionVin);

        if (await result.CountAsync() > 0)
        {
            // If the vehicle is not insured, insure it.
            await txn.Execute(
                "UPDATE Vehicles SET insured = TRUE WHERE vin = ?", ionVin);
            return true;
        }
        return false;
    });
}
```

------

### Logica di ripetizione dei tentativi


Per informazioni sulla logica di ripetizione integrata nel driver, vedere[Comprendere la politica dei nuovi tentativi con il driver in Amazon QLDB](driver-retry-policy.md).

### Implementazione di vincoli di unicità


QLDB non supporta indici univoci, ma puoi implementare questo comportamento nella tua applicazione.

Supponiamo di voler implementare un vincolo di unicità sul campo della tabella. `GovId` `Person` A tale scopo, è possibile scrivere una transazione che esegua le seguenti operazioni:

1. Asserisce che la tabella non ha documenti esistenti con un valore specificato`GovId`.

1. Inserisci il documento se l'asserzione ha esito positivo.

Se una transazione concorrente supera contemporaneamente l'asserzione, solo una delle transazioni verrà salvata correttamente. L'altra transazione avrà esito negativo con un'eccezione relativa al conflitto OCC.

Il seguente esempio di codice mostra come implementare questa logica di vincolo di unicità.

```
string govId = "TOYENC486FH";

Person person = new Person
{
    GovId = "TOYENC486FH",
    FirstName = "Brent"
};

await driver.Execute(async txn =>
{
    // Check if a document with GovId:TOYENC486FH exists
    // This is critical to make this transaction idempotent
    IAsyncResult<Person> result = await txn.Execute(txn.Query<Person>("SELECT * FROM Person WHERE GovId = ?", govId));

    // Check if there is a record in the cursor.
    int count = await result.CountAsync();
    if (count > 0)
    {
        // Document already exists, no need to insert
        return;
    }

    // Insert the document.
    await txn.Execute(txn.Query<Document>("INSERT INTO Person ?", person));
});
```

#### Utilizzo della libreria Ion


------
#### [ Async ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");

IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("GovId", valueFactory.NewString("TOYENC486FH"));
ionPerson.SetField("FirstName", valueFactory.NewString("Brent"));

await driver.Execute(async txn =>
{
    // Check if a document with GovId:TOYENC486FH exists
    // This is critical to make this transaction idempotent
    IAsyncResult result = await txn.Execute("SELECT * FROM Person WHERE GovId = ?", ionGovId);

    // Check if there is a record in the cursor.
    int count = await result.CountAsync();
    if (count > 0)
    {
        // Document already exists, no need to insert
        return;
    }

    // Insert the document.
    await txn.Execute("INSERT INTO Person ?", ionPerson);
});
```

------
#### [ Sync ]

```
IIonValue ionGovId = valueFactory.NewString("TOYENC486FH");

IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("GovId", valueFactory.NewString("TOYENC486FH"));
ionPerson.SetField("FirstName", valueFactory.NewString("Brent"));

driver.Execute(txn =>
{
    // Check if a document with GovId:TOYENC486FH exists
    // This is critical to make this transaction idempotent
    IResult result = txn.Execute("SELECT * FROM Person WHERE GovId = ?", ionGovId);

    // Check if there is a record in the cursor.
    int count = result.Count();
    if (count > 0)
    {
        // Document already exists, no need to insert
        return;
    }

    // Insert the document.
    txn.Execute("INSERT INTO Person ?", ionPerson);
});
```

------

**Nota**  
In questo esempio, consigliamo di avere un indice sul `GovId` campo per ottimizzare le prestazioni. Senza un indice attivo`GovId`, le istruzioni possono avere una maggiore latenza e possono anche portare a eccezioni nei conflitti OCC o a timeout delle transazioni.

## Lavorare con Amazon Ion


Esistono diversi modi per elaborare i dati di Amazon Ion in QLDB. Puoi usare la [libreria Ion](https://github.com/amzn/ion-dotnet) per creare e modificare valori Ion. In alternativa, puoi utilizzare lo [Ion object Mapper per mappare](https://github.com/amzn/ion-object-mapper-dotnet) i *semplici vecchi oggetti CLR* (POCO) di C\$1 da e verso i valori Ion. La versione 1.3.0 del driver QLDB per.NET introduce il supporto per il mappatore di oggetti Ion.

Le sezioni seguenti forniscono esempi di codice per l'elaborazione di dati Ion utilizzando entrambe le tecniche.

**Contents**
+ [

### Importazione del modulo Ion
](#cookbook-dotnet.ion.import)
+ [

### Creazione di tipi di ioni
](#cookbook-dotnet.ion.creating-types)
+ [

### Ottenere un dump binario Ion
](#cookbook-dotnet.ion.getting-binary)
+ [

### Ottenere un dump di testo Ion
](#cookbook-dotnet.ion.getting-text)

### Importazione del modulo Ion


```
using Amazon.IonObjectMapper;
```

#### Utilizzo della libreria Ion


```
using Amazon.IonDotnet.Builders;
```

### Creazione di tipi di ioni


Il seguente esempio di codice mostra come creare valori Ion da oggetti C\$1 utilizzando il mappatore di oggetti Ion.

```
// Assumes that Person class is defined as follows:
// public class Person
// {
//     public string FirstName { get; set; }
//     public int Age { get; set; }
// }

// Initialize the Ion Object Mapper
IonSerializer ionSerializer = new IonSerializer();

// The C# object to be serialized
Person person = new Person
{
    FirstName = "John",
    Age = 13
};

// Serialize the C# object into stream using the Ion Object Mapper
Stream stream = ionSerializer.Serialize(person);

// Load will take in stream and return a datagram; a top level container of Ion values.
IIonValue ionDatagram = IonLoader.Default.Load(stream);

// To get the Ion value within the datagram, we call GetElementAt(0).
IIonValue ionPerson = ionDatagram.GetElementAt(0);

Console.WriteLine(ionPerson.GetField("firstName").StringValue);
Console.WriteLine(ionPerson.GetField("age").IntValue);
```

#### Utilizzo della libreria Ion


I seguenti esempi di codice mostrano i due modi per creare valori Ion utilizzando la libreria Ion.

**Uso di `ValueFactory`**

```
using Amazon.IonDotnet.Tree;
using Amazon.IonDotnet.Tree.Impl;

IValueFactory valueFactory = new ValueFactory();

IIonValue ionPerson = valueFactory.NewEmptyStruct();
ionPerson.SetField("firstName", valueFactory.NewString("John"));
ionPerson.SetField("age", valueFactory.NewInt(13));

Console.WriteLine(ionPerson.GetField("firstName").StringValue);
Console.WriteLine(ionPerson.GetField("age").IntValue);
```

**Uso di `IonLoader`**

```
using Amazon.IonDotnet.Builders;
using Amazon.IonDotnet.Tree;

// Load will take in Ion text and return a datagram; a top level container of Ion values.
IIonValue ionDatagram = IonLoader.Default.Load("{firstName: \"John\", age: 13}");

// To get the Ion value within the datagram, we call GetElementAt(0).
IIonValue ionPerson = ionDatagram.GetElementAt(0);

Console.WriteLine(ionPerson.GetField("firstName").StringValue);
Console.WriteLine(ionPerson.GetField("age").IntValue);
```

### Ottenere un dump binario Ion


```
// Initialize the Ion Object Mapper with Ion binary serialization format
IonSerializer ionSerializer = new IonSerializer(new IonSerializationOptions
{
    Format = IonSerializationFormat.BINARY
});

// The C# object to be serialized
Person person = new Person
{
    FirstName = "John",
    Age = 13
};

MemoryStream stream = (MemoryStream) ionSerializer.Serialize(person);
Console.WriteLine(BitConverter.ToString(stream.ToArray()));
```

#### Utilizzo della libreria Ion


```
// ionObject is an Ion struct
MemoryStream stream = new MemoryStream();
using (var writer = IonBinaryWriterBuilder.Build(stream))
{
    ionObject.WriteTo(writer);
    writer.Finish();
}

Console.WriteLine(BitConverter.ToString(stream.ToArray()));
```

### Ottenere un dump di testo Ion


```
// Initialize the Ion Object Mapper
IonSerializer ionSerializer = new IonSerializer(new IonSerializationOptions
{
    Format = IonSerializationFormat.TEXT
});

// The C# object to be serialized
Person person = new Person
{
    FirstName = "John",
    Age = 13
};

MemoryStream stream = (MemoryStream) ionSerializer.Serialize(person);
Console.WriteLine(System.Text.Encoding.UTF8.GetString(stream.ToArray()));
```

#### Utilizzo della libreria Ion


```
// ionObject is an Ion struct
StringWriter sw = new StringWriter();
using (var writer = IonTextWriterBuilder.Build(sw))
{
    ionObject.WriteTo(writer);
    writer.Finish();
}

Console.WriteLine(sw.ToString());
```

Per ulteriori informazioni sull'utilizzo di Ion, consulta la [documentazione di Amazon Ion](http://amzn.github.io/ion-docs/) su GitHub. Per altri esempi di codice sull'utilizzo di Ion in QLDB, vedere. [Utilizzo dei tipi di dati Amazon Ion in Amazon QLDB](driver-working-with-ion.md)