I have a class that has an enum property inside it. The property is written as a string to the database when saving the whole document because of the attribute in the .NET representation of the document below
public enum Status { Good, Bad }
public class Document
{
[BsonRepresentation(BsonType.String)]
public Status Status { get; set; }
// ...
}
Later when I want to update the value within a document without saving the whole document, I construct a filter like this:
var builder = Builders<T>.Update;
var filter = builder.Set(new StringFieldDefinition<T, Status>(fieldName), (Status)value);
var result = await Context.Collection.UpdateManyAsync(filter, update);
This unfortunately writes the integer value of the enum.
If I change the filter to this
var filter = builder.Set(new StringFieldDefinition<T, Status>(fieldName), value.ToString());
The driver will throw an InvalidCastException. How can I construct the filter properly? Is there another way to set the enum value directly without replacing the document?
It occurred to me that there might be a way to relate the single-field behavior back to the attribute on the whole document, but I can't seem to find out how to do that.