问题
I have a collection of BsonDocuments, for example:
MongoCollection<BsonDocument> products;
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);
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?
回答1:
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
}
These are the results that came out when I ran this sample. You could see the Text property ended up being saved as "NotText":
回答2:
If I understand correctly, conventions are only applied when auto-mapping. If you have a classmap, you need to explicitly call AutoMap()
to use conventions. Then you can modify the automapping, e.g.:
public class MyThingyMap : BsonClassMap<MyThingy>
{
public MyThingyMap()
{
// Use conventions to auto-map
AutoMap();
// Customize automapping for specific cases
GetMemberMap(x => x.SomeProperty).SetElementName("sp");
UnmapMember(x => x.SomePropertyToIgnore);
}
}
If you don't include a class map, I think the default is to just use automapping, in which case your convention should apply. Make sure you're registering the convention before calling GetCollection<T>
.
来源:https://stackoverflow.com/questions/15981897/how-to-force-mongo-to-store-members-in-lowercase