开发者

Persisting an ExpandoObject to MongoDB

开发者 https://www.devze.com 2023-02-12 05:55 出处:网络
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:

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, st开发者_如何转开发at.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?


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);


Also you can try to use

BsonValue.Create(stat.Value)


May be it will be better to use Array of dynamic objects. some thing like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消