Search code examples
c#mongodbbson

Serialize entity class containing IMongoQuery


My entity class is like this:

public class MyType
{
    public string Name { get; set; }
    public IMongoQuery MyQuery { get; set; }
}

I am not able to persist this with the default serializers, when MyQuery contains anything complex such as an $in.

BsonDocumentSerializer gives error:

 Element name '$in' is not valid because it starts with a '$'.

I assume I need a special serializer type attributed to MyQuery. I've tried BsonDocument, BsonString, BsonJavaScript - all cannont cast to MongoDB.Driver.QueryDocument, which is the type of object stored in MyQuery.

Does this require a custom IBsonSerializer?


Solution

  • This seems to work. Stores the query as a JSON string.

    public class QueryDocumentSerializer : BsonBaseSerializer
        {
            public override object Deserialize(MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
            {
                if (bsonReader.GetCurrentBsonType() == BsonType.Null)
                {
                    bsonReader.ReadNull();
                    return null;
                }
                else
                {
                    var value = bsonReader.ReadString();
                    var doc = BsonDocument.Parse(value);
                    var query = new QueryDocument(doc);
                    return query;
                }
            }
    
            public override void Serialize(MongoDB.Bson.IO.BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
            {
                if (value == null)
                {
                    bsonWriter.WriteNull();
                }
                else
                {
                    var query = (QueryDocument)value;
                    var json = query.ToJson();
                    bsonWriter.WriteString(json);
                }
            }
        }