我的代码使用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);
}
我没有得到文档更新。您知道我的迁移代码是什么问题。
谢谢
您调用一个异步方法,而await
使用异步方法_collection.UpdateOneAsync(query, update);
不是问题的根本原因,但是在这种情况下,您没有适当的异常处理。
要么await
使用相应的同步版本UpdateOne,要么
您可能还希望将ReplaceOne用作V1驱动程序的初始版本,并且也进行了整个文档的替换。以下内容应符合您的需求(尽管未测试)
...
var query = Builders<T>.Filter.Eq(queryExpression, id);
_collection.ReplaceOne(query, entity);
...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句