最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

MongoDB C# driver class mapping: map MongoDB nested fields to flat class - Stack Overflow

programmeradmin1浏览0评论

I’m trying to do a very simple thing, I want to map a MongoDB document with nested fields to a flat class like so:

Document:

{ 
    code: "123",
    data: {
        other_code: "456",
    }
}

Class:

public class MyClass 
{
    [BsonElement("code")]
    public string Code { get; set; }
    
    [BsonElement("data.other_code")] // <= syntax not supported for Deserialization
    public string OtherCode { get; set; }
}

And then I want to be able to use it in a typed query like this:

var filter = Builders<MyClass>.Filter.Where(x => x.OtherCode == "456")

The filter generated does uses my string with dot notation:

"data.other_code" : "456"

But when I execute the query with:

List<Myclass> results = collection.Find(filter).ToList();

The member OtherCode is not populated and stays NULL.

I know I can do something like this:

public class MyClass
{
    [BsonElement("code")]
    public string Code { get; set; }

    [BsonElement("data")]
    public Data Data { get; set; }

    [BsonIgnore]
    public string OtherCode => Data?.OtherCode

}

public class Data
{
    [BsonElement("other_code")]
    public string OtherCode{ get; set; }
}

But I would like not to have to create a class everytime I need to map a nested field.

I tried to write a custom BsonSerializer but the Deserialize method is never called.

Any thoughts on how I could do it ?

Thanks for your help !

发布评论

评论列表(0)

  1. 暂无评论