MongoDB C# Driver - Ignore fields on binding

后端 未结 3 1924
被撕碎了的回忆
被撕碎了的回忆 2020-12-04 21:10

When using a FindOne() using MongoDB and C#, is there a way to ignore fields not found in the object?

EG, example model.

public class UserModel
{
           


        
相关标签:
3条回答
  • 2020-12-04 21:42

    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);
    
    0 讨论(0)
  • 2020-12-04 21:46

    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.

    0 讨论(0)
  • 2020-12-04 21:49

    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.

    0 讨论(0)
提交回复
热议问题