Rick Rainey
Rick Rainey

Reputation: 11256

How to force mongo to store members in lowercase?

I have a collection of BsonDocuments, for example:

MongoCollection<BsonDocument> products;

When I do inserts into the collection, I want the member name to always be lowercase. After reading the documentation, it appears that ConventionPack is the way to go. So, I've defined one like this:

    public class LowerCaseElementNameConvention : IMemberMapConvention
{
    public void Apply(BsonMemberMap memberMap)
    {
        memberMap.SetElementName(memberMap.MemberName.ToLower());
    }

    public string Name
    {
        get { throw new NotImplementedException(); }
    }
}

And right after I get my collection instance I register the convention like this:

        var pack = new ConventionPack();
        pack.Add(new LowerCaseElementNameConvention());
        ConventionRegistry.Register(
            "Product Catalog Conventions",
            pack,
            t => true);

Unfortunately, this has zero effect on what is stored in my collection. I debugged it and found that the Apply method is never called.

What do I need to do differently to get my convention to work?

Upvotes: 4

Views: 3886

Answers (3)

Nikhil Sarvaiye
Nikhil Sarvaiye

Reputation: 1

You can define ConventionPack which is also part of their official document on Serialization. Like below which stores are property names as camel case. You can place while Configuring services/repositories

Official link https://mongodb.github.io/mongo-csharp-driver/1.11/serialization/[Mongo Db Serialization C#]1

            // For MongoDb Conventions
            var pack = new ConventionPack
            {
                new CamelCaseElementNameConvention()
            };

            ConventionRegistry.Register(nameof(CamelCaseElementNameConvention), pack, _ => true);

Upvotes: 0

JustinAngel
JustinAngel

Reputation: 16102

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":

Print out of Foos table with NotText properties

Upvotes: 3

Avish
Avish

Reputation: 4626

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>.

Upvotes: 1

Related Questions