How to force mongo to store members in lowercase?

扶醉桌前 提交于 2019-12-06 08:09:33
JustinAngel

In order to use IMemeberMapConvention, you must make sure to declare your conventions before the mapping process takes place. Or optionally drop existing mappings and create new ones.

For example, the following is the correct order to apply a convention:

        // first: create the conventions
        var myConventions = new ConventionPack();
        myConventions.Add(new FooConvention());

        ConventionRegistry.Register(
           "My Custom Conventions",
           myConventions,
           t => true);

        // only then apply the mapping
        BsonClassMap.RegisterClassMap<Foo>(cm =>
        {
            cm.AutoMap();
        });

        // finally save 
        collection.RemoveAll();
        collection.InsertBatch(new Foo[]
                               {
                                   new Foo() {Text = "Hello world!"},
                                   new Foo() {Text = "Hello world!"},
                                   new Foo() {Text = "Hello world!"},
                               });

Here's how this sample convention was defined:

public class FooConvention : IMemberMapConvention

    private string _name = "FooConvention";

    #region Implementation of IConvention

    public string Name
    {
        get { return _name; }
        private set { _name = value; }
    }

    public void Apply(BsonMemberMap memberMap)
    {
        if (memberMap.MemberName == "Text")
        {
            memberMap.SetElementName("NotText");
        }
    }

    #endregion
}

These are the results that came out when I ran this sample. You could see the Text property ended up being saved as "NotText":

If I understand correctly, conventions are only applied when auto-mapping. If you have a classmap, you need to explicitly call AutoMap() to use conventions. Then you can modify the automapping, e.g.:

public class MyThingyMap : BsonClassMap<MyThingy>
{
    public MyThingyMap()
    {
        // Use conventions to auto-map
        AutoMap(); 

        // Customize automapping for specific cases
        GetMemberMap(x => x.SomeProperty).SetElementName("sp"); 
        UnmapMember(x => x.SomePropertyToIgnore);
    }
}

If you don't include a class map, I think the default is to just use automapping, in which case your convention should apply. Make sure you're registering the convention before calling GetCollection<T>.

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