实现所有类BsonIgnoreExtraElements

Cle*_*ari 18 c# mongodb

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

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

McG*_*gle 27

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

var myConventions = new ConventionProfile();
myConventions.SetIgnoreExtraElementsConvention(new AlwaysIgnoreExtraElementsConvention()));
BsonClassMap.RegisterConventions(myConventions, (type) => true);
Run Code Online (Sandbox Code Playgroud)

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

编辑

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

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

  • 在最新版本的MongoDB C#Driver中,上面代码中使用的大多数类型都标记为"过时".所以更新(和更紧凑)的代码将是:`使用MongoDB.Bson.Serialization.Conventions; ConventionRegistry.Register("IgnoreExtraElements",新的ConventionPack {new IgnoreExtraElementsConvention(true)},type => true);` (4认同)
  • @Evereq谢谢.我已经使用您的修复程序编辑了我的答案,如果你没问题的话. (2认同)