简体   繁体   English

C#Mongodb CRUD运算符更新方法

[英]C# Mongodb CRUD operators Update method

I am new to c# and mongodb and having trouble resolving my update method for my api. 我是C#和mongodb的新手,无法解决我的api的更新方法。 I am following this tutorial here . 我在这里关注本教程。 I am trying to fix the deprecation on it as I go, I am currently stuck on this portion 我正在尝试解决折旧问题,目前我停留在此部分

  public void Update(ObjectId id,Product p)
    {
        p.Id = id;
        var res = Query<Product>.EQ(pd => pd.Id,id);
        var operation = Update<Product>.Replace(p);
        _db.GetCollection<Product>("Products").Update(res,operation);
    }

I have updated it in my code to look like this. 我已经在代码中对其进行了更新,使其看起来像这样。

 public void Update(ObjectId id, Product p)
    {
        p.ProductId = id;
        var res = Builders<Product>.Filter.Eq(pd => pd.ProductId, id);
        var operation = Builders<Product>.Update(p);
        _db.GetCollection<Product>("Product").UpdateOne(res, operation);
    }

My problem is on the .update I cant us it as a method... so what is the correct way to construct this update method? 我的问题是在.update上,我无法将其作为一种方法...所以构造此更新方法的正确方法是什么? thanks in advance for any and all help. 在此先感谢您提供的所有帮助。

You are using the Builders incorrectly 您使用的构建器不正确

Builders<Product>.Update

Is not a method, it exposes a number of update operations you can use, ie Set, AddToSet etc 这不是一种方法,它公开了许多您可以使用的更新操作,例如Set,AddToSet等。

Depending what you are trying to achieve, you would use it as follows, if you want to update individual fields you can use this: 根据要实现的目标,可以按以下方式使用它,如果要更新单个字段,可以使用此方法:

var operation = Builders<Product>.Update.Set(u => u.SomeField, "SomeValue");

And you can chain them together, ie 您可以将它们链接在一起,即

var operation = Builders<Product>
    .Update
        .Set(u => u.SomeField, "SomeValue")
        .Set(u => u.SomeOtherField, "SomeOtherValue");

So using your code (which looks like you are filtering for a particular product Id, and then updating that very same field) 因此,请使用您的代码(看起来您正在过滤特定的产品ID,然后更新该字段)

public void Update(ObjectId id, Product p)
{
    var res = Builders<Product>.Filter.Eq(pd => pd.ProductId, id);
    var operation = Builders<Product>.Update.Set(u => u.ProductId, id);
    _db.GetCollection<Product>("Product").UpdateOne(res, operation);
}

Where as if you wanted to replace a document entirely, you might use ReplaceOne() instead of Update 如果您想完全替换文档,则可以使用ReplaceOne()而不是Update

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM