c# - Mongodb 约定包

标签 c# mongodb

如何在 C# 中使用 MongoDB ConventionPack 我有以下代码:

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

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

最佳答案

你需要在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);
        }
    }
}

关于c# - Mongodb 约定包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19521626/

相关文章:

javascript - 在 Angular 中调用 $post 时如何使用 MVC 重定向

node.js - 遍历整个 mongo 数据库的方法太大而无法加载?

javascript - 从 Angular Controller 获取数据并将其显示在 html View 上出现错误

c# - 如何使用 Monotouch 对话框显示 UIPickerView?

Mongodb:似乎不遵守上限大小限制

java - Morphia 在保存基本实体时抛出内部异常

mongodb - 具有MongoDB镜像的docker-maven-plugin在启动时挂起

c# - 使用 log4net 批量记录到 SQL Server

c# - 在 Windows 8.1 上全新安装 Visual Studio 2013 后出现 ASP.NET MVC Razor 错误

c# - 为什么 .NET 中有 5 个版本的定时器类?