简体   繁体   English

MongoDB中的部分更新C#驱动程序 - 字典问题

[英]Partial Update in MongoDB C# Driver - Dictionary issue

I'm trying to build a generic method to handle all my partial updates via MongoDB C# driver, using the following method: 我正在尝试使用以下方法构建一个通用方法来处理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;
}

I had to struggle for a while until I found the solution to handle primitive types via BsonValue and non-primitive types via BsonDocument. 我不得不挣扎一段时间,直到我找到解决方案通过BsonValue处理原始类型和通过BsonDocument处理非原始类型。 Everything worked well, until...We've created an object which holds a dictionary. 一切都运作良好,直到...我们创建了一个包含字典的对象。 The insert works perfectly, but once it goes into update (using this method) - it cannot be deserialized any more. 插入工作完美,但一旦进入更新(使用此方法) - 它不能再反序列化。 Looking at the object in the Mongo before and after the update indicates that it's not the same object anymore - after the update it has additional _t field holds "System.Collections.Generic.Dictionary`2[System.String,[SomeObject, SomeObjectAssembly]]" 在更新之前和之后查看Mongo中的对象表明它不再是同一个对象 - 在更新之后它有额外的_t字段保存“System.Collections.Generic.Dictionary`2 [System.String,[SomeObject,SomeObjectAssembly] ]”

So I'm starting to question my implementation... 所以我开始质疑我的实施......

Any idea what am I doing wrong? 知道我做错了什么吗?

Thanks, Nir. 谢谢,Nir。

With the courtesy of Robert Stam, the issue was resolved. 在Robert Stam的礼貌下,问题得到了解决。 It's all described in the Jira item. 这些都在Jira项目中描述。 Thank you! 谢谢!

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

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