Oluwafemi
Oluwafemi

Reputation: 14889

Linq to Mongodb dynamic update function

I am trying to update a collection dynamically by using generics. I have a working solution which is:

 MongoCollection symbolcollection= database.GetCollection<Symbol>("Symbols")  
var query3 = Query<Symbol>.EQ(e => e.Id, ("0000000000021325640.0");  
var update = Update<Symbol>.Set(e => e.Name, "abc"); // update modifiers  
symbolcollection.Update(query3, update); 

But my question is how can I update an item in a collection dynamically without explicitly declaring the collection type?

I tried something like this:

var query = Query.EQ("_id", new BsonObjectId(ObjectId.Parse(id)));
        var update = Update<TEntity>.Set(e => e, entity);
        var collection = GetCollection();
        collection.Update(query, update);

but it throws an exception:

An exception of type 'System.ArgumentNullException' occurred in MongoDB.Driver.dll but was not handled in user code

Exception Message: Value cannot be null. Parameter name: name

Is there a solution to this or is the working solution the only way to achieve this?

Upvotes: 2

Views: 3200

Answers (2)

Peyman
Peyman

Reputation: 3138

You can pass Action to method

public void Update(ObjectId id, Expression<Func<Entity , object>> updateExpr , object value)
{
    var query = Query.EQ("_id", new BsonObjectId(id));
    var update = Update<TEntity>.Set(updateExpr, value);
    var collection = GetCollection();
    collection.Update(query, update);
}

And call like:

Update(ObjectId.GenerateNewId(), x => x.Name, "NAME_VALUE");

Upvotes: 1

Oluwafemi
Oluwafemi

Reputation: 14889

I finally got it working by building the query before passing it into the final method to do the update:

 var symbolToUpdate = Update<Symbol>.Set(e => e.Name, symbol.Name);
            UpdateItem(symbolToUpdate, id);

    public void UpdateItem(UpdateBuilder<TEntity> symbolToUpdate, string id)
            {
                var query = Query.EQ("_id", new BsonObjectId(ObjectId.Parse(id)));
                var collection = GetCollection();
                collection.Update(query, symbolToUpdate);
            }

Upvotes: 1

Related Questions