来自C#中嵌套元素的MongoDB Map类

时间:2016-02-12 12:27:59

标签: c# mongodb mongodb-.net-driver

我已经注册了一个班级来从餐馆集合中提取地址:

BsonClassMap.RegisterClassMap<RestaurantAddress>(map =>
{
    map.MapMember(c => c.Id).SetElementName(("_id"));
    map.MapMember(c => c.Building).SetElementName("address.building");
    map.MapMember(c => c.Street).SetElementName("address.street");
    map.MapMember(c => c.ZipCode).SetElementName("address.zipcode");
});

Mongo文档如下:

{
    "_id" : ObjectId("56bb82621ff72e0d9ba267cb"),
    "address" : {
        "building" : "6409",
        "coord" : [ 
            -74.005289, 
            40.628886
        ],
        "street" : "11 Avenue",
        "zipcode" : "11219"
    },
    "borough" : "Brooklyn",
    "cuisine" : "American ",
    "grades" : [ 
        {
            "date" : ISODate("2014-07-18T00:00:00.000Z"),
            "grade" : "A",
            "score" : 12
        }, 
        {
            "date" : ISODate("2013-07-30T00:00:00.000Z"),
            "grade" : "A",
            "score" : 12
        }
    ],
    "name" : "Regina Caterers",
    "restaurant_id" : "40356649"
}

当我获得文档时,嵌套元素都是null:

[Test]
public void DeserializeToAddress()
{
    var collection = _database.GetCollection<RestaurantAddress>("grades");

    var address = collection.Find(a => a.Id == new ObjectId("56bb82621ff72e0d9ba267cb")).Limit(1).Single();

    Assert.That(address.Id, Is.Not.Null);
    Assert.That(address.Building, Is.Not.Null);
    Assert.That(address.Street, Is.Not.Null);
}

我应该如何引用嵌套元素?

要序列化的类是:

internal class RestaurantAddress
{
    public ObjectId Id { get; set; }
    public string Building { get; set; }
    public string Street { get; set; }
    public string ZipCode { get; set; }
    public Point CoordsPoint { get; set; }
}

Currenlty,我没有为CoordsPoint对象提供任何帮助。这是为了以后的练习。

1 个答案:

答案 0 :(得分:0)

我们目前不支持将嵌套元素拉出到父文档中。这将是一个功能请求。您可以在CSHARP项目下的jira.mongodb.org上提交。或者,如果您愿意,可以编写自定义序列化程序来处理此特定方案。

克雷格