c# - 如何在 MongoDB .Net 中更新插入文档?

标签 c# .net mongodb-.net-driver mongodb-csharp-2.0

我添加了一个 UpdateCustomer 方法,该方法传入要保存到数据库的修改后的客户。但在更新的文档上调用 ReplaceOneAsync 时,我遇到了错误。

我咨询过以下exampleapi reference ,两者都声明传递 ReplaceOneAsync filterdocument 参数。

但是由于参数不正确而引发的具体错误如下:

Error   1   The best overloaded method match for 'MongoDB.Driver.IMongoCollection<MongoDBApp.Models.CustomerModel>.ReplaceOneAsync(MongoDB.Driver.FilterDefinition<MongoDBApp.Models.CustomerModel>, MongoDBApp.Models.CustomerModel, MongoDB.Driver.UpdateOptions, System.Threading.CancellationToken)' has some invalid arguments 

Error   2   Argument 2: cannot convert from 'MongoDB.Bson.BsonDocument' to 'MongoDBApp.Models.CustomerModel'    

有人对理解该错误有任何提示吗?

UpdateCustomer 方法:

public async Task UpdateCustomer(CustomerModel customer)
{          
    var collection = StartConnection();
    var filter = Builders<CustomerModel>.Filter.Where(x => x.Id == customer.Id);

    BsonDocument doc = new BsonDocument();

    doc["_id"] = customer.Id;
    doc["firstName"] = customer.FirstName;
    doc["lastName"] = customer.LastName;
    doc["email"] = customer.Email;

    //error thrown here on the ReplaceOneAsync params..
    await collection.ReplaceOneAsync(filter, doc);           
}

以及关联的StartConnection方法:

private static IMongoCollection<CustomerModel> StartConnection()
{
    var client = new MongoClient(connectionString);
    var database = client.GetDatabase("orders");
    //Get a handle on the customers collection:
    var collection = database.GetCollection<CustomerModel>("customers");
    return collection;
}

最佳答案

您需要一直使用类型化集合,这意味着插入 CustomerModel 的实例,而不是 BsonDocument:

await collection.ReplaceOneAsync(filter, customer);

或者将无类型文档与 BsonDocument 一起使用,但从一开始就这样做:

var collection = database.GetCollection<BsonDocument>("customers");

您收到这些编译错误是因为您混合了这两个选项。

关于c# - 如何在 MongoDB .Net 中更新插入文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33876799/

相关文章:

c# - 为什么不能在泛型中要求运算符重载

c# - 允许您隐式地将 List<ChildClass> 视为 List<ParentClass> 的 C# 功能的名称是什么

c# - 参数绑定(bind)的.net核心路由列表

c# - ILogger 访问函数 Log<TState>(LogLevel logLevel

.net - 什么是封装?它实际上是如何隐藏数据的?

c# - Gridview DataSource 有行,但 GridView 没有

c# - 为什么 `GetFormat` 被调用两次?

c# - Mongodb,linq 驱动程序。如何使用变量或语句构造包含

c# - 如何将 mongo 集合转换为接口(interface) C#

c# - 如何更新 MongoDB 文档中的 <byte, string> 字典