如何强制mongo将成员存储为小写? [英] How to force mongo to store members in lowercase?
问题描述
我有一个BsonDocuments集合,例如:
I have a collection of BsonDocuments, for example:
MongoCollection<BsonDocument> products;
当我确实插入到集合中时,我希望成员名称始终为小写.阅读文档之后,ConferencePack似乎是必经之路.所以,我已经定义了这样一个:
When I do inserts into the collection, I want the member name to always be lowercase. After reading the documentation, it appears that ConventionPack is the way to go. So, I've defined one like this:
public class LowerCaseElementNameConvention : IMemberMapConvention
{
public void Apply(BsonMemberMap memberMap)
{
memberMap.SetElementName(memberMap.MemberName.ToLower());
}
public string Name
{
get { throw new NotImplementedException(); }
}
}
在我获得集合实例之后,我就注册了这样的约定:
And right after I get my collection instance I register the convention like this:
var pack = new ConventionPack();
pack.Add(new LowerCaseElementNameConvention());
ConventionRegistry.Register(
"Product Catalog Conventions",
pack,
t => true);
不幸的是,这对我的收藏夹中存储的内容影响为零.我调试了它,发现Apply方法从未调用过.
Unfortunately, this has zero effect on what is stored in my collection. I debugged it and found that the Apply method is never called.
要使我的公约生效,我需要做些什么?
What do I need to do differently to get my convention to work?
推荐答案
为了使用IMemeberMapConvention,必须确保在进行映射过程之前声明约定.或选择删除现有的映射并创建新的映射.
In order to use IMemeberMapConvention, you must make sure to declare your conventions before the mapping process takes place. Or optionally drop existing mappings and create new ones.
例如,以下是应用约定的正确顺序:
For example, the following is the correct order to apply a convention:
// 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!"},
});
以下是该示例约定的定义方式:
Here's how this sample convention was defined:
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":
These are the results that came out when I ran this sample. You could see the Text property ended up being saved as "NotText":
这篇关于如何强制mongo将成员存储为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!