c# - 如何强制mongo以小写形式存储成员?

标签 c# mongodb mongodb-.net-driver mlab

我有一个 BsonDocuments 的集合,例如:

MongoCollection<BsonDocument> products;

当我向集合中插入时,我希望成员名称始终为小写。阅读文档后,ConventionPack 似乎是可行的方法。所以,我定义了这样一个:

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

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

在我得到我的集合实例后,我立即注册了这样的约定:

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

不幸的是,这对我收藏中存储的内容影响为零。我调试了一下,发现从来没有调用过 Apply 方法。

我需要做哪些不同的事情才能让我的约定生效?

最佳答案

为了使用 IMemeberMapConvention,您必须确保在映射过程发生之前声明您的约定。或者可选择删除现有映射并创建新映射。

例如,以下是应用约定的正确顺序:

        // 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!"},
                               });

下面是这个示例约定的定义方式:

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
}

这些是我运行此示例时得出的结果。您可以看到 Text 属性最终被保存为“NotText”:

Print out of Foos table with NotText properties

关于c# - 如何强制mongo以小写形式存储成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15981897/

相关文章:

c# - C#中using关键字的使用

php - MongoDB PHP : How do I get ObjectId with a JSON feed?(它是空白的)

c# - ASP.NET 2.0 C# 应用程序因 NTDLL 上的内存访问冲突而崩溃

c# - 如何从 MongoDB 中的 ChangeStream 过滤对特定字段的更新

c# - 如何删除字符串的定义部分?

c# - 统一激活和停用游戏对象

javascript - Meteor:如何在 mongodb 集合中存储和检索文件?

c# - 从 2.0 MongoDb c# 驱动程序获取结果

c# - LINQ 连接多对多关系

mongodb - 如何列出 mongo shell 中的所有用户?