Implement for all classes BsonIgnoreExtraElements

前端 未结 2 1733
南方客
南方客 2021-01-01 12:26

I\'m using mongDb with MongoDrive, I wonder how I can implement to all my classes the [BsonIgnoreExtraElements].

I know there is a way through the <

2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-01 12:45

    Use the SetIgnoreExtraElementsConvention method (from the Conventions section of the C# Driver Serialization Tutorial):

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

    The parameter (type) => true is a predicate depending on the class type, that determines whether to apply the convention. So per your requirement it should simply return true regardless; but you could use this to set/exclude the convention on given types if you wanted.

    Edit

    Per Evereq's comment, the above is obsolete. Now use:

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

提交回复
热议问题