Partial update in MongoDB C # Driver - issue with dictionary release

I am trying to create a general method for handling all my partial updates using the C # MongoDB driver using the following method:

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 fight for a while, until I found a solution to process primitive types through BsonValue and non-primitive types through BsonDocument. Everything worked fine so far ... We created an object that contains a dictionary. The insert works fine, but once it goes into the update (using this method), it can no longer be deserialized. Looking at the object in Mongo before and after the update, he indicates that he is not the same object anymore - after the update he has an additional _t field. "System.Collections.Generic.Dictionary`2 [System.String, [SomeObject, SomeObjectAssembly]]"

, ...

, ?

, Nir.

+5
1

. . !

0

All Articles