Mongodb公约包

for*_*ect 14 c# mongodb

如何在c#中使用mongodb ConventionPack我有以下代码:

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

约定包是否自动附加到this.Collection?当我加载一个新对象时,它会自动保持这种情况吗?我是否必须在类声明中添加标签(如数据合同)?

mne*_*syn 20

您需要在以下位置注册包ConventionRegistry:

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

如果要全局应用它,可以用更简单的方法替换最后一个参数t => true.

序列化和反序列化的工作示例代码(驱动程序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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我发现,为了使骆驼箱正常工作,我需要在实例化我的集合之前调用`ConventionRegistry.Register()`(例如`db.GetCollection &lt;TDocument&gt;()`)。否则,我会得到不同的结果/奇怪的行为。 (2认同)