5
我試圖建立一個通用的方法來處理通過MongoDB的C#驅動程序的所有我的部分更新,使用下面的方法:部分更新 - 字典問題
public bool UpdateObject<T>(UpdatableObject<T> updatableObject)
where T : new()
{
var builder = GenerateMongoUpdateBuilder(updatableObject.ModifiedFields);
var collection = GetCollection<T>();
var result = collection.Update(Query.EQ("_id", BsonValue.Create(updatableObject.Id)), builder, new MongoUpdateOptions { Flags = UpdateFlags.Multi });
return result.UpdatedExisting;
}
private static UpdateBuilder GenerateMongoUpdateBuilder(Dictionary<string, object> modifiedFields)
{
var builder = new UpdateBuilder();
foreach (var modifiedField in modifiedFields)
{
var type = modifiedField.Value.GetType();
if (type.IsPrimitive || type.IsValueType || (type == typeof(string)))
{
builder.Set(modifiedField.Key, BsonValue.Create(modifiedField.Value));
}
else
{
builder.Set(modifiedField.Key, modifiedField.Value.ToBsonDocument());
}
}
return builder;
}
我不得不爲奮鬥直到我找到解決方案通過BsonValue處理原始類型並通過BsonDocument處理非原始類型。一切運行良好,直到...我們創建了一個包含字典的對象。該插入完美地工作,但一旦進入更新(使用此方法) - 它不能被反序列化了。在更新之前和之後查看Mongo中的對象表明它不再是同一個對象 - 在更新後它有另外的_t字段保存「System.Collections.Generic.Dictionary」[System.String,[SomeObject,SomeObjectAssembly] ]」
所以我開始懷疑我的實現......
任何想法,我究竟做錯了什麼?
謝謝, Nir。
聽起來很像一個bug。我建議你得到更好的repro指令,然後前往他們的[jira站點](https://jira.mongodb.org/browse/CSHARP)來報告它 – kelloti
Dictionary在你做什麼時會結束。 ToBsonDocument()呢? –
這是結果:{「_t」:「System.Collections.Generic.Dictionary'2 [System.String,[SomeObject,SomeObjectdll]]」,「_v」:{「f5030d52-cd70-404f-a3b4-072b6261e2c3」 :{「_id」:0,「Name」:「Test」},...這裏的附加條目... – nirpi