'DynamoDB object persistence with System.TimeSpan throws System.InvalidOperationException

I try to save a class with a TimeSpan property.

public class MyItem
{
    public TimeSpan MyTimeSpan {get;set;} = TimeSpan.Zero
}

when i try to save the object with following code...

IDynamoDBContext _context;
MyItem item = new MyItem();
...
await _context.SaveAsync(item);

... an exception is thrown System.InvalidOperationException: Type System.TimeSpan is unsupported, it cannot be instantiated

Someone has an idea how to store TimeSpan into dynamoDB?



Solution 1:[1]

It seems dynamodb does not support TimeSpan. https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes.String

However you can use a converter to do so

public class MyItem
{
    [DynamoDBProperty(typeof(TimeSpanConverter))]
    public TimeSpan MyTimeSpan {get;set;} = TimeSpan.Zero
}

the converter you have to write yourself.

public class TimeSpanConverter : IPropertyConverter
{
    public DynamoDBEntry ToEntry(object value)
    {
        var timeSpan = value as TimeSpan?;
        if (!timeSpan.HasValue) throw new ArgumentOutOfRangeException(nameof(value));

        return new Primitive(timeSpan.Value.TotalSeconds.ToString(), true);
    }

    public object FromEntry(DynamoDBEntry entry)
    {
        Primitive primitive = entry as Primitive;
        return primitive == null || primitive.Value == null
            ? (TimeSpan?)null
            : TimeSpan.FromSeconds(primitive.AsLong());
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mat