Case insensitive property mapping

别说谁变了你拦得住时间么 提交于 2019-12-23 03:13:03

问题


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"
}

to map to this class:

public MyObj
{
    public int Id {get; set;}
    public string Foo {get; set;}
}

回答1:


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; }
}

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/

Update

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.

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


来源:https://stackoverflow.com/questions/17556948/case-insensitive-property-mapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!