Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How does one use a mongodb ConventionPack in c# I have the following code:

        MongoDatabase Repository = Server.GetDatabase(RepoName);
        this.Collection = Repository.GetCollection<T>(CollectionName);
        var myConventions = new ConventionPack();
        myConventions.Add(new CamelCaseElementNameConvention());

Does the convention pack automatically attach to this.Collection? When I load in a new object will it automatically persist it as this case? Do I have to add tags in my class declaration (like a data contract)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
534 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to register the pack in the ConventionRegistry:

var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register("camel case",
                            pack,
                            t => t.FullName.StartsWith("Your.Name.Space."));

If you want to apply this globally, you can replace the last param with something simpler like t => true.

Working sample code that serializes and de-serializes (driver 1.8.20, mongodb 2.5.0):

using System;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;

namespace playground
{
    class Simple
    {
        public ObjectId Id { get; set; }
        public String Name { get; set; }
        public int Counter { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MongoClient client = new MongoClient("mongodb://localhost/test");
            var db = client.GetServer().GetDatabase("test");
            var collection = db.GetCollection<Simple>("Simple");
            var pack = new ConventionPack();
            pack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camel case", pack, t => true);
            collection.Insert(new Simple { Counter = 1234, Name = "John" });
            var all = collection.FindAll().ToList();
            Console.WriteLine("Name: " + all[0].Name);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...