Persisting an ExpandoObject to MongoDB
Asked Answered
C

3

6

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?

Caracara answered 22/2, 2011 at 1:42 Comment(3)
Which C# MongoDB Driver are you using?Sher
Can you post complete example, something like test case? So i'll check it. Thanks.Flippant
@Bugai13, the code doesn't exist in this form anymore, but here's the process: (1) create an ExpandoObject (2) Attach arbitrary properties of type Single, Int32, and String (3) Try to read them back and call Object.ToBson() on them.Caracara
P
9

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);
Photoactive answered 21/12, 2011 at 1:48 Comment(0)
A
1

Also you can try to use

BsonValue.Create(stat.Value)
Assail answered 23/3, 2011 at 16:52 Comment(0)
A
0

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 }
      }
}
Assail answered 22/2, 2011 at 8:18 Comment(3)
Galimy, how to index for this dynamicArray only City in place that all the array(C# off.)?Kapellmeister
as i know mongo doesn't allow to index by conditionAssail
This isn't a workable solution with my current project. I don't know what fields I'll have at runtime and they don't store type information with themselves.Caracara

© 2022 - 2024 — McMap. All rights reserved.