简体   繁体   English

使用mongo C#驱动程序,如何序列化自定义对象数组以便存储它?

[英]Using the mongo C# driver, how to serialize an array of custom object in order to store it?

I have a product document that contains an array of documents. 我有一个包含一系列文档的产品文档。 For example 例如

{
 id: 1,
 name: "J-E-L-L-O",
 store:[{id: 1,
    name: "Store X"},
    {id: 2,
    name: "Store Y"}]
}

I would like to change the name of "Store Y" to Store Z", for instance. At the time, I don't know the index of the object. So, I pull the entire array, find the object to update, change the name, and then attempt to set the value of "store" with the updated array. 我想将“Store Y”的名称更改为“Store Z”,例如。当时,我不知道对象的索引。所以,我拉出整个数组,找到要更新的对象,更改名称,然后尝试使用更新的数组设置“store”的值。

productCollection.Update(query, Update.Set("store", storeList.ToBsonDocument()));

However, I am getting an error: "An Array value cannot be written to the root level of a BSON document." 但是,我收到一个错误: "An Array value cannot be written to the root level of a BSON document."

I think I just need to know how to serialize the array of custom objects to an array of BsonDocuments. 我想我只需要知道如何将自定义对象数组序列化为BsonDocuments数组。

Thanks in advance for your help. 在此先感谢您的帮助。

Unfortunately I had the same problem and ended up making an extension method to help me get around it. 不幸的是我遇到了同样的问题,并最终制作了一个扩展方法来帮助我解决它。

    public static BsonArray ToBsonDocumentArray(this IEnumerable list)
    {
        var array = new BsonArray();
        foreach (var item in list)
        {
            array.Add(item.ToBson());
        }
        return array;
    }

so you should be able to do: 所以你应该能够做到:

productCollection.Update(query, Update.Set("store", storeList.ToBsonDocumentArray()));

The exception says that you cannot convert an array/list into a BsonDocument. 例外情况表示您无法将数组/列表转换为BsonDocument。 I think that you are looking to convert storeList to a [BsonArray][1] . 我认为你正在寻找将storeList转换为[BsonArray][1]

If storeList is already an array of BsonDocument or some IEnumerable<T> where to can be converted to a BsonDocument , the you should not need to cast the storeList variable at all. 如果storeList已经阵列BsonDocument或一些IEnumerable<T>在何处可以被转换为一个BsonDocument ,则你应该不需要施放storeList在所有变量。

you should use 你应该使用

BsonDocument.Parse(storeList);

instead of 代替

storeList.ToBsonDocument()

Little edit for the accepted answer function: 接受答案功能的编辑很少:

public static BsonArray ToBsonDocumentArray(this IEnumerable list)
    {
        var array = new BsonArray();
        foreach (var item in list)
        {
            array.Add(item);
        }
        return array;
    }

we don't need to convert item.ToBson(). 我们不需要转换item.ToBson()。 There is already an implicit conversion from string to bson.Thats the reason i was getting an error message " A String value cannot be written to the root level of a BSON document. " 已经存在从字符串到bson的隐式转换。这就是我收到错误消息“ 无法将字符串值写入BSON文档的根级别”的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM