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.
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.
How can I create a class map for B that use a different mapping for A only inside it?
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With