MongoDB C# Driver - Ignore fields on binding

微笑、不失礼 提交于 2019-11-27 18:40:32
i3arnon

Yes. Just decorate your UserModel class with the BsonIgnoreExtraElements attribute:

[BsonIgnoreExtraElements]
public class UserModel
{
    public ObjectId id { get; set; }
    public string Email { get; set; }
}

As the name suggests, the driver would ignore any extra fields instead of throwing an exception. More information here - Ignoring Extra Elements.

Yet Another possible solution, is to register a convention for this.

This way, we do not have to annotate all classes with [BsonIgnoreExtraElements].

Somewhere when creating the mongo client, setup the following:

        var pack = new ConventionPack();
        pack.Add(new IgnoreExtraElementsConvention(true));
        ConventionRegistry.Register("My Solution Conventions", pack, t => true);
Aviram Fireberger

Yes. Another way (instead of editing you model class) is to use RegisterClassMap with SetIgnoreExtraElements.

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

BsonClassMap.RegisterClassMap<UserModel>(cm =>
{
     cm.AutoMap();
     cm.SetIgnoreExtraElements(true);
});

You can read more about ignoring extra elements using class mapping here - Ignoring Extra Elements.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!