不区分大小写的属性映射 [英] Case insensitive property mapping
问题描述
将MongoDB文档序列化为POCO时,有什么方法可以使属性映射不区分大小写?例如,我想要这份文件:
When serializing a MongoDB document to a POCO is there any way to make properties map case insensitive? For example I'd like this document:
{
"id": "1"
"foo": "bar"
}
以映射到此类:
public MyObj
{
public int Id {get; set;}
public string Foo {get; set;}
}
推荐答案
为此,我认为您将有2个选择.
To do that I think you will have 2 options.
第一个方法是手动编写一个类映射
The first would be to write out a class map manually
BsonClassMap.RegisterClassMap<MyClass>(cm => {
cm.AutoMap();
cm.GetMemberMap(c => c.Foo).SetElementName("foo");
});
第二个方法是使用以下属性装饰您的类
The second would be to decorate your class with the following attributes
public class MyObj
{
[BsonElement("id")]
public int Id { get; set; }
[BsonElement("foo")]
public string Foo { get; set; }
}
CSharp驱动程序团队在以下链接上有一个很好的序列化教程
The CSharp driver team have a good tutorial on serialization on the following link
http://docs.mongodb.org /ecosystem/tutorial/serialize-documents-with-the-csharp-driver/
我刚刚尝试了以下内容,并且对我有用,显然,我确定这是您代码的简化版本,但您可以猜测一下它的外观.
I have just tried the following and this works for me, obviously I'm sure this is a much more simplified version of your code but taking a guess at how it might look.
我已经分别注册了两个类映射,并将BsonKnownType添加到基类.
I have registered the two class maps separately and added the BsonKnownType to the base class.
[BsonKnownTypes(typeof(GeoJSONObject))]
public class Point
{
public string Coordinates { get; set; }
}
public class GeoJSONObject : Point
{
public string Type { get; set; }
}
static void Main(string[] args)
{
var cn = new MongoConnectionStringBuilder("server=localhost;database=MyTestDB;");
var settings = MongoClientSettings.FromConnectionStringBuilder(cn);
var client = new MongoClient(settings);
BsonClassMap.RegisterClassMap<Point>(cm =>
{
cm.AutoMap();
cm.GetMemberMap(c => c.Coordinates).SetElementName("coordinates");
});
BsonClassMap.RegisterClassMap<GeoJSONObject>(cm =>
{
cm.AutoMap();
cm.GetMemberMap(c => c.Type).SetElementName("type");
});
var result = client.GetServer()
.GetDatabase("MyTestDB")
.GetCollection("MyCol")
.Find(Query.EQ("type", BsonValue.Create("xxxx")));
}
这篇关于不区分大小写的属性映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!