Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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?

like image 973
tmm360 Avatar asked Dec 18 '14 00:12

tmm360


1 Answers

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());
like image 62
2 revs, 2 users 67% Avatar answered Oct 14 '22 14:10

2 revs, 2 users 67%