![](/img/trans.png)
[英]Using C# MongoDB Driver, how to serialize a collection of object referements?
[英]Using the mongo C# driver, how to serialize an array of custom object in order to store it?
我有一个包含一系列文档的产品文档。 例如
{
id: 1,
name: "J-E-L-L-O",
store:[{id: 1,
name: "Store X"},
{id: 2,
name: "Store Y"}]
}
我想将“Store Y”的名称更改为“Store Z”,例如。当时,我不知道对象的索引。所以,我拉出整个数组,找到要更新的对象,更改名称,然后尝试使用更新的数组设置“store”的值。
productCollection.Update(query, Update.Set("store", storeList.ToBsonDocument()));
但是,我收到一个错误: "An Array value cannot be written to the root level of a BSON document."
我想我只需要知道如何将自定义对象数组序列化为BsonDocuments数组。
在此先感谢您的帮助。
不幸的是我遇到了同样的问题,并最终制作了一个扩展方法来帮助我解决它。
public static BsonArray ToBsonDocumentArray(this IEnumerable list)
{
var array = new BsonArray();
foreach (var item in list)
{
array.Add(item.ToBson());
}
return array;
}
所以你应该能够做到:
productCollection.Update(query, Update.Set("store", storeList.ToBsonDocumentArray()));
例外情况表示您无法将数组/列表转换为BsonDocument。 我认为你正在寻找将storeList
转换为[BsonArray][1]
。
如果storeList
已经阵列BsonDocument
或一些IEnumerable<T>
在何处可以被转换为一个BsonDocument
,则你应该不需要施放storeList
在所有变量。
你应该使用
BsonDocument.Parse(storeList);
代替
storeList.ToBsonDocument()
接受答案功能的编辑很少:
public static BsonArray ToBsonDocumentArray(this IEnumerable list)
{
var array = new BsonArray();
foreach (var item in list)
{
array.Add(item);
}
return array;
}
我们不需要转换item.ToBson()。 已经存在从字符串到bson的隐式转换。这就是我收到错误消息“ 无法将字符串值写入BSON文档的根级别”的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.