Press "Enter" to skip to content

.NET, DynamoDB, and DateTime

There is an issue when using the AWSSDK.DynamoDBv2 NuGet package; it doesn’t like Nullable<DateTime> values.  For some reason, the built in converters do not handle these properties correctly should the value be null.

To remedy the situation, you need to create an IPropertyConverter implementation, and then assign it to the property via the DynamoDBProperty attribute.  Here is the IPropertyConverter implementation that I used:

public class DateConverter : IPropertyConverter
{
    public object FromEntry(DynamoDBEntry entry)
    {
        var dateTime = entry?.AsString();
        if (string.IsNullOrEmpty(dateTime))
            return null;

        if (!DateTime.TryParse(dateTime, out DateTime value))
            throw new ArgumentException("entry parameter must be a validate DateTime value.", nameof(entry));
        else
            return value;
    }

    public DynamoDBEntry ToEntry(object value)
    {
        if (value == null)
            return new DynamoDBNull();

        if (value.GetType() != typeof(DateTime) && value.GetType() != typeof(DateTime?))
            throw new ArgumentException("value parameter must be a DateTime or a Nullable<DateTime>.", nameof(value));

        return ((DateTime)value).ToString();
    }
}

Once that’s defined, you then apply it to your Nullable<DateTime> property by using the 2nd parameter of the DynamoDBProperty attribute:

[DynamoDBProperty("created", typeof(DateConverter))]
public DateTime? Created { get; set; }

Be First to Comment

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

WP Twitter Auto Publish Powered By : XYZScripts.com