序列化包含IMongoQuery的实体类

时间:2014-06-23 15:27:06

标签: c# mongodb bson

我的实体类是这样的:

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

当MyQuery包含任何复杂内容(如$ in)时,我无法使用默认序列化程序保留此内容。

BsonDocumentSerializer给出错误:

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

我假设我需要一个归因于MyQuery的特殊序列化器类型。我已经尝试过BsonDocument,BsonString,BsonJavaScript - 所有东西都被强制转换为MongoDB.Driver.QueryDocument,这是MyQuery中存储的对象类型。

这需要自定义IBsonSerializer吗?

2 个答案:

答案 0 :(得分:1)

适用于C#驱动程序2.0:

public class MyIMongoSerializer : SerializerBase<IMongoQuery>
{
    public override void Serialize(BsonSerializationContext context,
                                   BsonSerializationArgs args,
                                   IMongoQuery value)
    {
        if (value == null)
        {
            context.Writer.WriteNull();
        }
        else
        {
            var query = (IMongoQuery)value;
            var json = query.ToJson();
            context.Writer.WriteString(json);
        }
    }

    public override IMongoQuery Deserialize(BsonDeserializationContext context,
                                            BsonDeserializationArgs args)
    {
        if (context.Reader.GetCurrentBsonType() == BsonType.Null)
        {
            context.Reader.ReadNull();
            return null;
        }
        else
        {
            var value = context.Reader.ReadString();
            var doc = BsonDocument.Parse(value);
            var query = new QueryDocument(doc);
            return query;
        }
    }
}

并注释属性以使用序列化程序:

[BsonSerializer(typeof(MyIMongoSerializer))]
public IMongoQuery filter { get; set; }

答案 1 :(得分:0)

这似乎有效。将查询存储为JSON字符串。

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);
            }
        }
    }