使用mongo C#驱动程序,如何序列化自定义对象数组以进行存储? [英] Using the mongo C# driver, how to serialize an array of custom object in order to store it?

查看:160
本文介绍了使用mongo C#驱动程序,如何序列化自定义对象数组以进行存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一系列文档的产品文档.例如

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"}]
}

例如,我想将"Store Y"的名称更改为"Store Z".当时,我不知道对象的索引.因此,我拉整个数组,找到对象更新,更改名称,然后尝试使用更新后的数组设置存储"的值.

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.

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

但是,我遇到一个错误:"An Array value cannot be written to the root level of a BSON document."

However, I am getting an error: "An Array value cannot be written to the root level of a BSON document."

我想我只需要知道如何将自定义对象的数组序列化为BsonDocuments的数组即可.

I think I just need to know how to serialize the array of custom objects to an array of BsonDocuments.

预先感谢您的帮助.

推荐答案

不幸的是,我遇到了同样的问题,最终提出了一种扩展方法来帮助我解决问题.

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

所以您应该可以:

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

这篇关于使用mongo C#驱动程序,如何序列化自定义对象数组以进行存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆