C# 驱动程序 v2 中的更新文档从驱动程序 v1 迁移
Update document in C# driver v2 migrate from Driver v1
我的代码使用 C# Mongo 驱动程序版本 1 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));
}
然后我将代码更改为 C# 驱动程序版本 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); ;
}
我使用 (controller
):
调用
public void Update(PostModel post)
{
_postRepo.Posts.Update(s => s.Id, post.Id, post);
}
我没有得到文档update.Do你知道我的迁移代码有什么问题。
谢谢
您在没有 await
和 _collection.UpdateOneAsync(query, update);
的情况下调用异步方法,这不是问题的根本原因,但在这种情况下您没有适当的异常处理。
要么await
要么使用相应的同步版本UpdateOne
您可能还想使用 ReplaceOne,因为您的初始版本的 V1 驱动程序也进行了整个文档替换。以下应该符合您的需要(虽然未测试)
...
var query = Builders<T>.Filter.Eq(queryExpression, id);
_collection.ReplaceOne(query, entity);
...
我的代码使用 C# Mongo 驱动程序版本 1 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));
}
然后我将代码更改为 C# 驱动程序版本 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); ;
}
我使用 (controller
):
public void Update(PostModel post)
{
_postRepo.Posts.Update(s => s.Id, post.Id, post);
}
我没有得到文档update.Do你知道我的迁移代码有什么问题。
谢谢
您在没有 await
和 _collection.UpdateOneAsync(query, update);
的情况下调用异步方法,这不是问题的根本原因,但在这种情况下您没有适当的异常处理。
要么await
要么使用相应的同步版本UpdateOne
您可能还想使用 ReplaceOne,因为您的初始版本的 V1 驱动程序也进行了整个文档替换。以下应该符合您的需要(虽然未测试)
...
var query = Builders<T>.Filter.Eq(queryExpression, id);
_collection.ReplaceOne(query, entity);
...