Using C# MongoDB Driver, how to serialize a collection of object referements?
BsonClassMap
is not your solution, you should write your custom IBsonSerializer
for B
classI just implemeted the Serialize
method, the Deserilze
works same way.
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:
BsonSerializer.RegisterSerializer(typeof(B), new BSerialzer());