Using the C # MongoDB Driver, how to serialize a collection of referee objects?

I have two classes, for 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 create class maps with BsonClassMap.RegisterClassMap () for both A and B, because they are stored in relative collections.

The problem starts when I try to match B, because I need to match collection A as links to external documents with some additional information, so in this case I only need to display identifiers and names.

How to create a class map for B that use a different map for A only inside it?

+6
source share
1 answer

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()); 
+4
source

Source: https://habr.com/ru/post/979818/


All Articles