Friday, June 2, 2017

In the course of developing of developing a c# ASP.NET application that reads and writes data to an AWS DynamoDB instance I came across the problem storing and retrieving Enum data. Ideally I wanted to store the data as a string rather than int in the database, but unfortunately using the AWS SDK nuget package there is no support for doing this. 

The solution? Write a custom converter using the
IPropertyConverter interface provided by AWSSDK framework. See below:

    public class DynamoDBTypeConvertedEnum<T> : IPropertyConverter
    {
        public object FromEntry(DynamoDBEntry entry)
        {
            Primitive primitive = entry as Primitive;
            if (primitive == null)
                throw new ArgumentOutOfRangeException();
            var parsedEnum = (T)Enum.Parse(typeof(T), primitive.ToString());

            return parsedEnum;
        }

        public DynamoDBEntry ToEntry(object value)
        {
            if (!(value is T))
                throw new ArgumentOutOfRangeException();
            string enumAsString = Enum.GetName(typeof(T), value);

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

When applying this to our class which represents the table in DynamoDB you decorate it as such:

    [DynamoDBTable("MyData")]
    public class MyData
    {
        [DynamoDBHashKey]
        public string Id { get; set; }
        [DynamoDBProperty]
        public string Title { get; set; }

        [DynamoDBProperty(typeof(DynamoDBTypeConvertedEnum<MyEnum>))]
        public MyEnum MyEnumType { get; set; }
    }

    public enum MyEnum
    {
        EnumerationOne,
        EnumerationTwo
    }

In this way we can store the data in a readable way and also use the power of enums in our code.

No comments:

Post a Comment