实现所有类BsonIgnoreExtraElements

我在MongoDrive中使用mongDb,我想知道如何在我的所有类中实现[BsonIgnoreExtraElements]

我知道通过ConventionProfile有一种方法,但我不知道如何实现它。

使用SetIgnoreExtraElementsConvention方法(来自C#驱动程序序列化教程的约定部分):

 var myConventions = new ConventionProfile(); myConventions.SetIgnoreExtraElementsConvention(new AlwaysIgnoreExtraElementsConvention())); BsonClassMap.RegisterConventions(myConventions, (type) => true); 

参数(type) => true是一个谓词,取决于类类型,它决定是否应用约定。 因此,根据您的要求,无论如何都应该返回true; 但如果需要,可以使用它来设置/排除给定类型的约定。

编辑

根据Evereq的评论,上述内容已经过时。 现在使用:

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

基本上,

mongoDB使您能够将文档存储在单个集合中,每个集合都可以拥有自己的模式。 如果您具有关系数据库的背景,那么这是一个巨大的变化。 在关系数据库中,每个表都有一个静态模式,如果不更改表的结构,则不能偏离。 在下面的示例中,我定义了一个Person类和一个派生自Person类的PersonWithBirthDate类。 这些都可以存储在mongoDB数据库的同一集合中。 在这种情况下,假设文档存储在Persons集合中。

查看示例代码 –

 public class Person { public string FirstName { get; set; } public string LastName { get; set; } } public class PersonWithBirthDate : Person { public DateTime DateOfBirth { get; set; } } 

现在,您可以轻松检索文档并让mongoDB C#驱动程序将文档反序列化到PersonWithBirthDate类中。 但是,如果查询Persons集合并尝试让驱动程序将数据反序列化为Person类,则会遇到问题。 您将收到一个错误,指出有些元素无法反序列化。 通过将[BsonIgnoreExtraElements]属性添加到Person类,可以轻松修复此问题。 您可以在下面看到修改后的类。 这将指示驱动程序忽略它无法反序列化为相应属性的任何元素。 使用该属性,可以将Persons集合中的任何文档解密到Person类而不会出现错误。

 [BsonIgnoreExtraElements] public class Person { public string FirstName { get; set; } public string LastName { get; set; } } public class PersonWithBirthDate : Person { public DateTime DateOfBirth { get; set; } } 

我希望这会清除你的理解。