[英]Serialize entity class containing IMongoQuery
我的實體類是這樣的:
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?
適用於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; }
這似乎有效。 將查詢存儲為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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.