繁体   English   中英

C# MongoDB 字段映射

[英]C# MongoDB Field mapping

我有以下设置有效,但是当 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();

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

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

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

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

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

暂无
暂无

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

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