[英]Using C# MongoDB Driver, how to serialize a collection of object referements?
I have two classes, example: 我有两个类,例如:
public class A
{
public string Id { get; set; }
public string Name { get; set; }
// Other properties...
}
public class B
{
public string Id { get; set; }
public ICollection<A> ReferredAObjects { get; set; }
// Other properties...
}
I have create class maps with BsonClassMap.RegisterClassMap() for both A and B because they are stored separated into relative collections. 我已经为A和B创建了带有BsonClassMap.RegisterClassMap()的类映射,因为它们被分开存储为相对集合。
The problem starts when I try to map B, because I need to map the collection of A as references to external documents with some additional informations, so in this case I need to map only ids and names. 当我尝试映射B时问题就开始了,因为我需要将A的集合映射为带有一些额外信息的外部文档的引用,所以在这种情况下我只需要映射id和名称。
How can I create a class map for B that use a different mapping for A only inside it? 如何为B创建一个类映射,仅在其中使用不同的映射?
BsonClassMap
is not your solution, you should write your custom IBsonSerializer
for B
class I just implemeted the Serialize
method, the Deserilze
works same way. BsonClassMap
不是你的解决方案,你应该为B
类我编写自定义IBsonSerializer
我刚刚实现了Serialize
方法, Deserilze
工作方式相同。
public class BSerialzer : IBsonSerializer
{
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
{
throw new NotImplementedException();
}
public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
{
throw new NotImplementedException();
}
public IBsonSerializationOptions GetDefaultSerializationOptions()
{
throw new NotImplementedException();
}
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
{
var b = (B)value;
bsonWriter.WriteStartDocument();
bsonWriter.WriteString("_id", b.Id);
bsonWriter.WriteStartArray("refs");
foreach (var refobj in b.ReferredAObjects)
{
bsonWriter.WriteString(refobj.Id);
}
bsonWriter.WriteEndArray();
bsonWriter.WriteEndDocument();
}
}
for a sample below objects 对于对象下面的示例
var a0 = new A
{
Id = "0",
Name = "0",
};
var a1 = new A
{
Id = "1",
Name = "1",
};
var b = new B
{
Id = "b0",
ReferredAObjects = new Collection<A> { a0, a1 }
};
collection.Insert(b);
will produce output like: 将产生如下输出:
{
"_id" : "b0",
"refs" : [
"0",
"1"
]
}
Just remember to register this Sterilizer
at program start-up: 只需记住在程序启动时注册此
Sterilizer
:
BsonSerializer.RegisterSerializer(typeof(B), new BSerialzer());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.