【问题标题】:C# MongoDB Field mappingC# MongoDB 字段映射
【发布时间】:2021-03-01 01:49:23
【问题描述】:

我有以下设置,但是当 MongoDB 集合有额外的字段时,程序会因错误而崩溃

"System.FormatException: 元素 'FriendName' 不匹配任何 MyApp.User 类的字段或属性"

我的印象是 MongoDB 驱动程序只能映射在 C# 类中声明的字段。有没有解决的办法 ?谢谢。

MongoDB - 集合User

{ Name: "Allen" , Age: 22, Address: "Sample Address", FriendName = "Sue"}


public class User
{
  public string Name {get;set;}
  public int Age {get; set;}
  public string Address {get;set; }
}


 _db.GetCollection<User>("User").Find(f => f.Name == "Allen").FirstOrDefault();

【问题讨论】:

    标签: c# mongodb


    【解决方案1】:

    MongoDB C# 驱动程序期望 BSON 文档中的所有字段都与您的 .NET 类匹配 - 这是默认行为。您可以使用BsonIgnoreExtraElements 属性更改它

    [BsonIgnoreExtraElements]
    public class User
    {
        [BsonId]
        public ObjectId Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }
    

    【讨论】:

      【解决方案2】:

      我还找到了一种在访问数据库之前调用以下 ConventionPack 来全局设置 BsonIgnoreExtraElements 的方法。

       var conventionpack = new ConventionPack() { new IgnoreExtraElementsConvention(true) };
       ConventionRegistry.Register("IgnoreExtraElements", conventionpack, type => true);
      

      【讨论】:

        【解决方案3】:

        如果您需要在 mongo 中映射属性,请检查此

        https://mongodb.github.io/mongo-csharp-driver/2.7/reference/bson/mapping/
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-01-05
          • 2023-01-01
          • 2020-12-10
          • 2011-11-26
          • 2020-04-17
          • 2016-07-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多