2017-09-06 56 views
0

具有以下類:BsonExtraElements字典<串,對象>和自定義類作爲值失敗序列

public class Article 
{ 
    [BsonId] 
    [BsonRepresentation(BsonType.ObjectId)] 
    public string Id { get; set; } 

    public string Name { get; set; } 

    [BsonExtraElements()] 
    public Dictionary<string, Object> OtherData { get; set; } 
} 

我想此對象添加到詞典和寫入到數據庫中:

public class Bird 
{ 
    [BsonElement("_n")] 
    [BsonRequired] 
    public string Name { get; set; } 
    [BsonElement("_s")] 
    [BsonRequired] 
    public string Species { get; set; } 
    [BsonElement("_a")] 
    [BsonRequired] 
    public int Age { get; set; } 
} 

var col = db.GetCollection<Article>("articles"); 

var art = new Article 
{ 
    Name = "Blu" 
}; 

art.OtherData = new System.Collections.Generic.Dictionary<string, object>() 
{ 
    { "bird" , new Bird { Name = "Jerry", Age = 4, Species = "European starling" } } 
}; 

col.InsertOne(art); 

但是這個失敗,出現以下異常信息:System.ArgumentException:「.NET類型鳥不能映射到BsonValue」

如果我刪除[BsonExtraElements]在致敬,一切順利,文章在數據庫中結束。爲什麼是這樣?屬性如何防止序列化?由於該屬性不在那裏,我的這個自定義類可以由驅動程序序列化。

使用驅動程序版本2.4.4

+0

我報道這個在MongoDB的[JIRA ](https://jira.mongodb.org/browse/CSHARP-2035)。他們已經研究並回答:「這不是真正的預期行爲。我們現在假設BsonExtraElements字典中的所有值都是BsonValue的實例,或者可以簡單地轉換爲BsonValue。我們應該能夠通過使用序列化器來轉換更復雜的值,比如您的Bird類。 我們會考慮在未來的版本中支持這個.' –

回答

1

官方文檔(http://mongodb.github.io/mongo-csharp-driver/1.11/serialization/):

你可以設計你的類能夠處理可能一BSON文檔中反序列化過程中發現有任何多餘的元素。爲此,您必須擁有BsonDocument類型的屬性,並且必須將該屬性標識爲應該包含找到的任何其他元素的屬性(或者您可以將該屬性命名爲「ExtraElements」,以便默認的ExtraElementsMemberConvention可以找到它自動)。

public MyClass { 
// fields and properties 
[BsonExtraElements] 
public BsonDocument CatchAll { get; set; } 
} 

長話短說,它需要在使用[BsonExtraElements]標籤是BsonDocument類型。

乾杯!

編輯:我懂了工作,加入

{ "bird" , new Bird { Name = "Jerry", Age = 4, Species = "European starling" }.ToBsonDocument() } 
+0

謝謝你的回答!然而,你鏈接的文檔是舊的。我使用的是C#驅動程序的2.4版本。在那裏可以將'[BsonExtraElements]'添加到[dictionary](http://mongodb.github.io/mongo-csharp-driver/2.0/reference/bson/mapping/#supporting-extraelements)。 '這樣做,你必須有一個BsonDocument類型的屬性(或IDictionary )' –

+0

哦,你沒有指定驅動程序版本,所以我很難這樣做。您是否嘗試將成員重命名爲ExtraElements? – BOR4

+0

我給出了一個去,但我仍然得到與重命名的字段相同的錯誤。我還編輯了這個問題,以包含驅動程序版本。 –

0

使用[BsonDictionaryOptions(DictionaryRepresentation.Document)]代替

public class Article 
{ 
    [BsonId] 
    [BsonRepresentation(BsonType.ObjectId)] 
    public string Id { get; set; } 

    public string Name { get; set; } 

    [BsonDictionaryOptions(DictionaryRepresentation.Document)] 
    public Dictionary<string, Object> OtherData { get; set; } 
} 

這將產生JSON像

{ 
    "_id": ObjectId("5a468f3e28fad22e08c4fa6b"), 
    "Name": "Sanjay", 
    "OtherData": { 
     "stringData": "val1", 
     "boolVal": true, 
     "someObject": { 
      "key1": "val1", 
      "key2": "val2" 
     }, 
     ... 
    } 

} 
相關問題