蒙戈德布公约包
本文关键字:布公约 | 更新日期: 2023-09-27 18:36:21
如何在C#中使用MongoDB ConventionPack
我有以下代码:
MongoDatabase Repository = Server.GetDatabase(RepoName);
this.Collection = Repository.GetCollection<T>(CollectionName);
var myConventions = new ConventionPack();
myConventions.Add(new CamelCaseElementNameConvention());
约定包是否自动附加到此包。收集?
当我加载一个新对象时,它会自动像这种情况一样保留它吗?
我是否必须在类声明中添加标记(如数据协定)?
您需要
在ConventionRegistry
中注册包:
var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register("camel case",
pack,
t => t.FullName.StartsWith("Your.Name.Space."));
如果要全局应用此功能,可以将最后一个参数替换为更简单的参数,例如 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);
}
}
}