BsonClassMap
not your solution, you have to write your own IBsonSerializer
for the B
class. I just executed the Serialize
method, Deserilze
works the same.
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 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 output output, for example:
{ "_id" : "b0", "refs" : [ "0", "1" ] }
Remember to register this Sterilizer
when starting the program:
BsonSerializer.RegisterSerializer(typeof(B), new BSerialzer());
source share