MongoDB C# Driver: Ignore Property on Insert

前端 未结 5 1662
余生分开走
余生分开走 2021-02-03 18:48

I am using the Official MongoDB C# Drive v0.9.1.26831, but I was wondering given a POCO class, is there anyway to ignore certain properties from getting inserted.

For ex

5条回答
  •  走了就别回头了
    2021-02-03 19:13

    You should probably want to combine the two attributes BsonIgnoreExtraElements and BsonIgnore. The reason for that is although BsonIgnore will not insert the "IsOwner" property to you DB but if you have "old" instances in your DB that contained this field and you will remove this fields from your model in the feature or extend your "GroceryList" class and use your new class in the DB will get an exception:

    "Element 'IsOwner' does not match any field or property of class."

    Another way (instead of editing you model class) is to use "Register Class Map" with "SetIgnoreExtraElements" and "UnmapMember" together.

    In your case just add this code when you initialize your driver:

    BsonClassMap.RegisterClassMap(cm =>
    {
         cm.AutoMap();
         cm.SetIgnoreExtraElements(true);
         cm.UnmapMember(m => m.IsOwner);
    });
    

    You can read more about Mongo Class Mapping in:

    http://mongodb.github.io/mongo-csharp-driver/2.0/reference/bson/mapping/

提交回复
热议问题