Search code examples
c#amazon-dynamodbobject-persistence

C# Equivalant of Javas @DynamoDBTyped(DynamoDBAttributeType.BOOL)


I had this question but there was no C# answer, only Java ones (DyanmoDb is storing value 1 instead of boolean value true) so posting this.

There is no way I know of that allows you to use the Object Persistence model for DynamoDB and ensure that boolean primitives stay "true"/"false" when put in a DynamoDB table. By default, they get turned into "1" and "0".

How can we ensure that a boolean field doesn't get turned into a 1/0 when put in DynamoDB?


Solution

  • @Dhruv's original converter saves as a string value rather than native bool. You can modify your property converter slightly to use the DynamoDBBool type and still use the document model as follows:

        public class DynamoDBNativeBooleanConverter : IPropertyConverter
        {
            public DynamoDBEntry ToEntry(object value) => new DynamoDBBool(bool.TryParse(value?.ToString(), out var val) && val);
            public object FromEntry(DynamoDBEntry entry) => entry.AsDynamoDBBool()?.Value;
        }
    

    This could be extended more to support for reading from string/number/etc in the FromEntry to handle legacy data scenarios if desired.