我有以下可用的设置,但是当MongoDB Collection包含多余的字段时,程序会因错误而崩溃
“ 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();
答案 0 :(得分: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; }
}
答案 1 :(得分:1)
我还找到了一种在访问数据库之前通过调用以下ConventionPack来全局设置BsonIgnoreExtraElements的方法。
var conventionpack = new ConventionPack() { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreExtraElements", conventionpack, type => true);
答案 2 :(得分:0)
如果您需要在 mongo 中映射属性,请检查此
https://mongodb.github.io/mongo-csharp-driver/2.7/reference/bson/mapping/