通过属性的C#MongoDB更新字段

问题描述

一个问题,假设我们有这样的类型:

public class Foo 
{
    [BsonId]
    public string Id { get; set; }    

    [BsonElement]
    protected string _bar;
    public string BarProperty { get => _bar; set => _bar = value; }
}

我想使用mongo update通过_bar更新BarProperty字段:

public void SetBar(string id,string bar)
{
    var f = Builders<Foo>.Filter.Eq(x => x.Id,id);
    var u = Builders<Foo>.Update.Set(x => x.BarProperty,bar);

    // `Collection` is IMongoCollection<Foo>
    Collection.UpdateOne(f,u);
}

更新后我们遇到了一些问题:

  1. _bar尚未更改;
  2. BarProperty出现在数据库中的对象中; (如果我使用[BsonIgnore]会导致错误-system.invalidOperationException: Unable to determine the serialization @R_342_4045@ion for x => x.BarProperty.

当我们更新了_bar(在数据库和实例中)并且BarProperty没有序列化时,有什么办法吗?

解决方法

唯一的方法是绕过要更新的实际字段名称。

public void SetBar(string id,string bar)
{
    var f = Builders<Foo>.Filter.Eq(x => x.Id,id);
    var u = Builders<Foo>.Update.Set("_bar",bar);

    Collection.UpdateOne(f,u);
}

您是否有理由不能公开酒吧财产?