

# AWS SDK for .NET 객체 지속성 모델을 사용하여 DynamoDB에서 임의 데이터 매핑
<a name="DynamoDBContext.ArbitraryDataMapping"></a>

지원되는 .NET 형식([지원되는 데이터 유형](DotNetSDKHighLevel.md#DotNetDynamoDBContext.SupportedTypes) 참조) 외에도 애플리케이션에서 직접적으로 Amazon DynamoDB 형식에 매핑되지 않는 형식을 사용할 수 있습니다. 데이터를 임의 형식에서 DynamoDB 형식으로 또는 그 반대로 변환할 수 있는 변환기가 있는 한 객체 지속성 모델은 임의 형식의 데이터 저장을 지원합니다. 객체를 저장하거나 로드하는 동안 변환기 코드가 데이터를 변환합니다.

클라이언트 측에서 어떤 유형도 생성할 수 있습니다. 그러나 테이블에 저장되는 데이터는 DynamoDB 형식 중 하나이며 쿼리 및 스캔이 진행되는 동안 DynamoDB에 저장되어 있는 데이터에 대해 데이터 비교가 수행됩니다.

다음의 C\$1 코드 예제에서는 `Book`, `Id`, `Title` 및 `ISBN` 속성을 사용하여 `Dimension` 클래스를 정의하고 있습니다. `Dimension` 속성은 `DimensionType`, `Height` 및 `Width` 속성을 기술하는 `Thickness`에 포함되어 있습니다. 이 예제 코드는 데이터를 `DimensionType` 및 DynamoDB 문자열 형식 간에 전환하는 변환기 메서드 `ToEntry` 및 `FromEntry`를 제공합니다. 예를 들어, `Book` 인스턴스를 저장할 때 변환기는 "8.5x11x.05"와 같은 책 `Dimension` 문자열을 생성합니다. 책을 검색하면 문자열이 `DimensionType` 인스턴스로 변환됩니다.

이 예제에서는 `Book` 유형을 `ProductCatalog` 테이블로 매핑합니다. 샘플 `Book` 인스턴스를 저장하고, 해당 인스턴스를 검색하고, 해당 차원을 업데이트하고, 업데이트된 `Book`을 다시 저장합니다.



다음 예제를 테스트하기 위한 단계별 지침은 [.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;
        }
    }
}
```