[英]c# BsonSerializer: deserialization through backing fields
I'm starting to work with MongoDB using official c# driver. 我开始使用官方c#驱动程序来使用MongoDB。 The problem is that I can't find a way to make bsonseriazer use fields (not properties) for setting the deserialized data and at the same time being able to use LINQ Api.
问题是我找不到使bsonseriazer使用字段(而不是属性)来设置反序列化数据并同时使用LINQ Api的方法。
When mapping my class, I use BsonClassMap.FieldMap(). 映射类时,我使用BsonClassMap.FieldMap()。 But this doesn't allow to use LINQ, since public properties remain unmapped.
但这不允许使用LINQ,因为公共属性仍未映射。 Is there a way in BsonSerializer to do mappings based on properties, but at the same time specify that these should be set directly via their backing fields?
BsonSerializer中有没有一种方法可以基于属性进行映射,但同时指定应直接通过其后备字段设置这些映射?
The reason I want to use fields for deserialization, is to omit custom validation rules that might be checked in setter. 我想使用字段进行反序列化的原因是省略了可能在setter中检查的自定义验证规则。
I think you should keep those validation rules even when the data comes from your own database. 我认为即使数据来自您自己的数据库,您也应该保留这些验证规则。 It's much cleaner, less bug-prone and is more secure.
它更清洁,更不易出错且更安全。
You can create your own BsonSerializer
s (or extend an existing one) that act which ever way you want. 您可以创建自己的
BsonSerializer
(或扩展现有的BsonSerializer
),该BsonSerializer
可以按您希望的方式运行。 I've made several of those and it's really simple. 我已经做了几个,这真的很简单。
You can have a bool _isInitialized = false;
你可以有一个
bool _isInitialized = false;
in your DTO
s that you set to true right after you get items from the MongoDB driver and forgo the validation rules until it is set. 在从MongoDB驱动程序获取项目之后立即设置为true的
DTO
,并放弃验证规则直到被设置。
I don't see another way to "split" the mapping to both the properties (for Linq
) and data members (for serialization) and I recommend the first option. 我看不到另一种将映射“拆分”到属性(对于
Linq
)和数据成员(对于序列化)的方法,我建议第一种选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.