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