tree em
tree em

Reputation: 21711

Update document in C# driver v2 migrate from Driver v1

My code using C# Mongo Driver Version1 Repository

        /// <summary>
        ///  Generic update method to update record on the basis of id
        /// </summary>
        /// <param name="queryExpression"></param>
        /// <param name="id"></param>
        /// <param name="entity"></param>
        public void Update(Expression<Func<T, string>> queryExpression, string id, T entity)
        {
           var query = Query<T>.EQ(queryExpression, id);
           _collection.Update(query, Update<T>.Replace(entity)); 
        }

And I change the code to C# driver version 2

    /// <summary>
    ///  Generic update method to update record on the basis of id


     /// </summary>
    /// <param name="queryExpression"></param>
    /// <param name="id"></param>
    /// <param name="entity"></param>
    public void Update(Expression<Func<T, string>> queryExpression, string id, T entity)
    {
       // var query = Query<T>.EQ(queryExpression, id);
        //_collection.Update(query, Update<T>.Replace(entity));


        var query = Builders<T>.Filter.Eq(queryExpression, id);
        var update = Builders<T>.Update.Set(queryExpression, id);
        _collection.UpdateOneAsync(query, update); ;

    }

I called by using (controller):

 public void Update(PostModel post)
        {
            _postRepo.Posts.Update(s => s.Id, post.Id, post);
        }

I did not get the document update.Do you know what is the problem with my migration code.

Thanks

Upvotes: 1

Views: 366

Answers (1)

DAXaholic
DAXaholic

Reputation: 35348

You call an asynchronous method without await with _collection.UpdateOneAsync(query, update); which is not the root cause of your problem but you have no proper exception handling in this case.
Either await it or use the corresponding synchronous version UpdateOne


You probably also rather want to use ReplaceOne as your initial version with the V1 driver also did a whole document replacement. The following should fit your needs (not tested though)

...
var query = Builders<T>.Filter.Eq(queryExpression, id);
_collection.ReplaceOne(query, entity);
...

Upvotes: 1

Related Questions