admin管理员组文章数量:1417472
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 !
本文标签: MongoDB C driver class mapping map MongoDB nested fields to flat classStack Overflow
版权声明:本文标题:MongoDB C# driver class mapping: map MongoDB nested fields to flat class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745267502a2650692.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论