簡體   English   中英

使用mongo C#驅動程序,如何序列化自定義對象數組以便存儲它?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM