Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persisting an ExpandoObject to MongoDB

I have an ExpandoObject with an arbitrary number of properties. I want to persist those properties to a MongoDB database as a BsonDocument. I try to do so 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, on calling the extension method ToBson() on object, I receive the following exception: WriteInt32 cannot be called when State is: Initial.

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

like image 503
Yes - that Jake. Avatar asked Feb 22 '11 01:02

Yes - that Jake.


1 Answers

It's very simple. ExpandoObject inherits IDictionary which works with BsonDocument out of the box.

dynamic data = new ExpandoObject();
var doc = new BsonDocument(data);
collection.Save(doc);
like image 169
Ryan Avatar answered Sep 22 '22 02:09

Ryan