C# MongoDB字段映射

3
我有以下设置,它可以工作,但是当MongoDB集合有额外的字段时,程序会崩溃并显示错误信息:“System.FormatException:元素'FriendName'与MyApp.User类中的任何字段或属性都不匹配”。我认为MongoDB驱动程序只能映射在C#类中声明的字段。是否有解决方法?谢谢。 MongoDB - 集合。
{ 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();
3个回答

3

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

1
如果您需要在Mongo中映射属性,请查看此内容。
https://mongodb.github.io/mongo-csharp-driver/2.7/reference/bson/mapping/

1
我还发现了一种方法,可以在访问数据库之前调用以下ConventionPack来全局设置BsonIgnoreExtraElements。
 var conventionpack = new ConventionPack() { new IgnoreExtraElementsConvention(true) };
 ConventionRegistry.Register("IgnoreExtraElements", conventionpack, type => true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接