Enum injected into MongoDB aggregate pipeline is not serialized as string in C#

Viewed 96

I have an aggregate pipeline I'm using to filter documents. A portion of this pipeline takes the form of:

new BsonDocument("$match", 
    new BsonDocument(
        new Dictionary<string, object>() {
            { "prompt_id", promptId },
            { "status", Status.Created }
        } 
    }
}

where Status is an enum defined like this:

public enum Status {

    [JsonConverter(typeof(StringEnumConverter))]
    [BsonRepresentation(BsonType.String)]
    Created,

    [JsonConverter(typeof(StringEnumConverter))]
    [BsonRepresentation(BsonType.String)]
    InProgress,

    [JsonConverter(typeof(StringEnumConverter))]
    [BsonRepresentation(BsonType.String)]
    Completed,

    [JsonConverter(typeof(StringEnumConverter))]
    [BsonRepresentation(BsonType.String)]
    Dropped
}

This definition of Status allows fields of that type to be serialized to/deserialized from a string in MongoDB. However, in my aggregate pipeline definition, it sends the value as an integer. I could fix this by replacing Status.Created with Status.Created.ToString() but I'd have to do that wherever the value occurs, which would be error-prone. My questions are:

  1. Is this a problem with the BsonDocument converting the enum value to an integer or is it a problem with the Dictionary?
  2. Is there a way to fix this with attributes/custom serializers on the enum instead of manually converting values to a string every single time?
0 Answers
Related