.NET, DynamoDB, and DateTime
Published September 10, 2018 by Jamie Nordmeyer
There is an issue when using the AWSSDK.DynamoDBv2 NuGet package; it doesn’t like Nullable
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
[DynamoDBProperty("created", typeof(DateConverter))]
public DateTime? Created { get; set; }