将 ExpandoObject 持久保存到 MongoDB
我有一个具有任意数量属性的 ExpandoObject。我想将这些属性作为 BsonDocument 保存到 MongoDB 数据库。我尝试使用以下代码执行此操作:
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;
}
但是,在调用对象上的扩展方法 ToBson() 时,我收到以下异常:当状态为:初始时,无法调用 WriteInt32。
我所知道的唯一 WrtieInt32 是 Marshall 类的静态方法。我这样做是错误的吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这很简单。
ExpandoObject
继承了IDictionary
,它可以开箱即用地与BsonDocument
配合使用。It's very simple.
ExpandoObject
inheritsIDictionary
which works withBsonDocument
out of the box.您也可以尝试使用
Also you can try to use
可能使用动态对象数组会更好。
像这样的事情:
May be it will be better to use Array of dynamic objects.
some thing like this: