Saving an ExpandoObject in MongoDB

I have an ExpandoObject with an arbitrary number of properties. I want to save these properties in a MongoDB database as a BsonDocument. I am trying to do this with the following code:

private BsonDocument GetPlayerDocument(IPlayer player)
{
    var ret = new BsonDocument();

    ret.Add("FirstName", player.FirstName).
        Add("LastName", player.LastName).
        Add("Team", player.Team).
        Add("Positions", new BsonArray(player.Positions));

    foreach (var stat in (IDictionary<String, Object>)player.Stats)
    {
        ret.Add(stat.Key, stat.Value.ToBson());
    }

    return ret;
}

However, when I call the ToBson () extension method on an object, I get the following exception: WriteInt32 cannot be called when State: Initial.

The only WrtieInt32 I know is the static method of the Marshall class. Am I approaching this wrong?

+5
source share
3 answers

It is very simple. ExpandoObjectinherits IDictionarythat works with BsonDocumentout of the box.

dynamic data = new ExpandoObject();
var doc = new BsonDocument(data);
collection.Save(doc);
+8
source

, . - :

someObject
{
      dynamicArray:
      {
           item : { Key: "Name", Value: "Jekke", Type:String }
           item : { Key: "Age", Value: "40", Type:int }
           item : { Key: "City", Value: "New York", Type:String }
      }
}
0

BsonValue.Create(stat.Value)
0

All Articles