2

我正在添加一个UpdateCustomer方法,将修改后的客户传递到数据库中。ReplaceOneAsync但是我在调​​用更新的文档时遇到了一个错误。

我已经查阅了以下示例api 参考,它们都表示要传递ReplaceOneAsyncafilterdocument参数。

但是具体的错误是因为参数不正确而抛出的,如下所述:

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;
}
4

2 回答 2

2

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

await collection.ReplaceOneAsync(filter, customer);

或者使用无类型的BsonDocument,但从一开始就这样做:

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

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

于 2015-11-23T17:27:07.293 回答
1

这对我有用

var filter = Builders.Filter.Where(x => x.Id == customer.Id); await Collection.ReplaceOneAsync(filter, item, new ReplaceOptions { IsUpsert = true });

于 2020-01-14T21:02:05.723 回答