

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à.

# Mappatura di dati arbitrari con DynamoDB utilizzando il modello di persistenza degli oggetti AWS SDK per .NET
<a name="DynamoDBContext.ArbitraryDataMapping"></a>

Oltre ai tipi .NET supportati (vedere [Tipi di dati supportati](DotNetSDKHighLevel.md#DotNetDynamoDBContext.SupportedTypes)), è possibile utilizzare i tipi dell'applicazione per i quali non vi è una mappatura diretta ai tipi di Amazon DynamoDB. Il modello di persistenza degli oggetti supporta la memorizzazione di dati di tipi arbitrari purché si fornisca il convertitore per convertire i dati dal tipo arbitrario al tipo DynamoDB e viceversa. Il codice convertitore trasforma i dati sia durante il salvataggio che durante il caricamento degli oggetti.

È possibile creare qualsiasi tipo sul lato client. Tuttavia, i dati memorizzati nelle tabelle sono uno dei tipi DynamoDB e durante la query e la scansione, tutti i confronti di dati effettuati sono rispetto ai dati memorizzati in DynamoDB.

L'esempio di codice C\$1 seguente definisce una classe `Book` con le proprietà `Id`, `Title`, `ISBN` e `Dimension`. La proprietà `Dimension` è di `DimensionType` che descrive le proprietà `Height`, `Width` e `Thickness`. Il codice di esempio fornisce i metodi del convertitore`ToEntry` e `FromEntry` per convertire i dati tra `DimensionType` e i tipi di stringa DynamoDB. Ad esempio, quando si salva un'istanza `Book`, il convertitore crea una stringa `Dimension` del libro come "8.5x11x.05". Quando recuperi un libro, converte la stringa in un'istanza `DimensionType`.

Nell'esempio viene mappato il tipo `Book` alla tabella `ProductCatalog`. Salva un'istanza `Book` di esempio, la recupera, aggiorna le sue dimensioni e salva di nuovo il `Book` aggiornato.



Per step-by-step istruzioni su come testare il seguente esempio, consulta. [Esempi di codice .NET](CodeSamples.DotNet.md)

**Example**  

```
using System;
using System.Collections.Generic;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.Runtime;
using Amazon.SecurityToken;

namespace com.amazonaws.codesamples
{
    class HighLevelMappingArbitraryData
    {
        private static AmazonDynamoDBClient client = new AmazonDynamoDBClient();

        static void Main(string[] args)
        {
            try
            {
                DynamoDBContext context = new DynamoDBContext(client);

                // 1. Create a book.
                DimensionType myBookDimensions = new DimensionType()
                {
                    Length = 8M,
                    Height = 11M,
                    Thickness = 0.5M
                };

                Book myBook = new Book
                {
                    Id = 501,
                    Title = "AWS SDK for .NET Object Persistence Model Handling Arbitrary Data",
                    ISBN = "999-9999999999",
                    BookAuthors = new List<string> { "Author 1", "Author 2" },
                    Dimensions = myBookDimensions
                };

                context.Save(myBook);

                // 2. Retrieve the book.
                Book bookRetrieved = context.Load<Book>(501);

                // 3. Update property (book dimensions).
                bookRetrieved.Dimensions.Height += 1;
                bookRetrieved.Dimensions.Length += 1;
                bookRetrieved.Dimensions.Thickness += 0.2M;
                // Update the book.
                context.Save(bookRetrieved);

                Console.WriteLine("To continue, press Enter");
                Console.ReadLine();
            }
            catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); }
            catch (AmazonServiceException e) { Console.WriteLine(e.Message); }
            catch (Exception e) { Console.WriteLine(e.Message); }
        }
    }
    [DynamoDBTable("ProductCatalog")]
    public class Book
    {
        [DynamoDBHashKey] //Partition key
        public int Id
        {
            get; set;
        }
        [DynamoDBProperty]
        public string Title
        {
            get; set;
        }
        [DynamoDBProperty]
        public string ISBN
        {
            get; set;
        }
        // Multi-valued (set type) attribute.
        [DynamoDBProperty("Authors")]
        public List<string> BookAuthors
        {
            get; set;
        }
        // Arbitrary type, with a converter to map it to DynamoDB type.
        [DynamoDBProperty(typeof(DimensionTypeConverter))]
        public DimensionType Dimensions
        {
            get; set;
        }
    }

    public class DimensionType
    {
        public decimal Length
        {
            get; set;
        }
        public decimal Height
        {
            get; set;
        }
        public decimal Thickness
        {
            get; set;
        }
    }

    // Converts the complex type DimensionType to string and vice-versa.
    public class DimensionTypeConverter : IPropertyConverter
    {
        public DynamoDBEntry ToEntry(object value)
        {
            DimensionType bookDimensions = value as DimensionType;
            if (bookDimensions == null) throw new ArgumentOutOfRangeException();

            string data = string.Format("{1}{0}{2}{0}{3}", " x ",
                            bookDimensions.Length, bookDimensions.Height, bookDimensions.Thickness);

            DynamoDBEntry entry = new Primitive
            {
                Value = data
            };
            return entry;
        }

        public object FromEntry(DynamoDBEntry entry)
        {
            Primitive primitive = entry as Primitive;
            if (primitive == null || !(primitive.Value is String) || string.IsNullOrEmpty((string)primitive.Value))
                throw new ArgumentOutOfRangeException();

            string[] data = ((string)(primitive.Value)).Split(new string[] { " x " }, StringSplitOptions.None);
            if (data.Length != 3) throw new ArgumentOutOfRangeException();

            DimensionType complexData = new DimensionType
            {
                Length = Convert.ToDecimal(data[0]),
                Height = Convert.ToDecimal(data[1]),
                Thickness = Convert.ToDecimal(data[2])
            };
            return complexData;
        }
    }
}
```