3

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?

2 Answers 2

8

@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.

Sign up to request clarification or add additional context in comments.

Comments

2

The one way we can do this is to use IPropertyConverter.

First, we need to create a class that extends the IPropertyConverter, and put in our desired logic. We need to describe the to and from logic.

public class DynamoDBNativeBooleanConverter : IPropertyConverter
    {
        public DynamoDBEntry ToEntry(object value) => (bool) value ? "true" : "false";

        public object FromEntry(DynamoDBEntry entry)
        {
            var val = bool.Parse(entry.AsPrimitive().Value.ToString());
            return val;
        }
    }

Then, we can use this class when we use our boolean attribute:

   ...
        
   [JsonProperty("can_flip")]
   [DynamoDBProperty("can_flip", typeof(DynamoDBNativeBooleanConverter))]
   public bool CanFlip { get; set; }
        
   ...

Using this, the data in DynamoDB tables will show up as "true" or "false", and when you consume it, it will be a boolean.

1 Comment

Recommend using bool.TryParse instead of bool.Parse if you don't want an exception thrown in the FromEntry implementation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.