C# 序列化包含IMongoQuery的实体类
我的实体类如下所示:C# 序列化包含IMongoQuery的实体类,c#,mongodb,bson,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 '
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中的对象类型
这是否需要自定义IBM序列化程序?这似乎可行。将查询存储为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);
}
}
}
适用于C#driver 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; }