▲相关特性MongoDB.Bson.Serialization.Attributes
MongoDB序列化特性官方文档:
[BsonIgnore]
[BsonElement]
[BsonIgnoreExtraElements]
[BsonExtraElements]
[BsonRepresentation(BsonType.String)]
2.可以忽略某些字段
[BsonIgnore]该标签用来禁止字段序列化,不保存数据库也不查询,即忽略。
3.支持默认值以及取别名
[BsonElement] 字段加上该标签,即使是private字段也会序列化(默认只序列化public字段),该标签还可以带一个string参数,给字段序列化指定别名。
[BsonIgnore]//忽略保存进数据库,禁止字段序列化。 public Entity Entity [BsonIgnore]//组件类中 public NavGraph[] graphs; //默认private不会序列化,加上BsonElement就会序列化 [BsonElement("C")] [BsonIgnoreIfNull] private HashSet<Component> components = new HashSet<Component>();
4.升级版本支持
[BsonIgnoreExtraElements] 该标签用在class上面,反序列化时用来忽略多余的字段,一般版本兼容需要考虑,低版本的协议需要能够反 序列化高版本的内容,否则新版本删除字段,旧版本结构反序列化会出错
5.支持额外的元素
[BsonExtraElements]
您可以将您的类设计为能够处理反序列化期间在BSON文档中可能发现的任何其他元素。为此,您必须具有BsonDocument(或IDictionary<string, object>)类型的属性,并且必须将该属性标识为应该包含找到的任何其他元素的属性。按照惯例,可以命名该成员ExtraElements。例如:
public MyClass { // fields and properties [BsonExtraElements] public BsonDocument CatchAll { get; set; } }
6.表示,枚举
[BsonRepresentation(BsonType.String)]
对于某些.NET基本类型,您可以控制要用来表示值的BSON类型。例如,您可以指定将char值表示为BSON Int32还是一字符BSON字符串:
默认情况下,枚举表示为其基础值。换句话说,纯枚举将表示为整数值。但是,可以指示驱动程序将枚举表示为字符串。
//告诉mongodb这个字段在数据库中的类型是String [BsonRepresentation(BsonType.String)] public AppType AppType { get; set; } //告诉mongodb这个字段在数据库中的类型是ObjectId [BsonRepresentation(BsonType.ObjectId)]
//默认是国际时间
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]//单独指定时区
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)]
DictionaryRepresentation有三个值可选:
[BsonRepresentation(BsonType.String)]
ET框架中,保存数据库组件需要继承 ISerializeToEntity接口。
[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfArrays)] public Dictionary<int, int> MyAreaDict = new Dictionary<int, int>();
//class上面,反序列化时用来忽略多余的字段,否则新版本加了字段,旧版本结构反序列化会出错 [BsonIgnoreExtraElements] public class CheckPointConfig : IConfig
[BsonElement] 字段加上该标签,即使是private字段也会序列化(默认只序列化public字段,readonly),该标签还可以带一个string参数,给字段序列化指定别名。
[BsonIgnoreExtraElements] public abstract class ComponentWithId : Component { [BsonIgnoreIfDefault] [BsonDefaultValue(0L)]//默认值 [BsonElement] [BsonId]//定义为主键,字段映射,告诉mongodb这个字段在数据库中对应_id,这个字段一般不需要在Json中体现出来,在序列化时被忽略 public long Id { get; set; } //默认是国际时间 [BsonDateTimeOptions(Kind = DateTimeKind.Local)]//单独指定时区
MongoDB.Driver中的Bson特性
namespace MongoDB.Driver { [BsonElement("max")] public TValue Max => _max; [BsonElement("count")] public long Count { get; private set; }
namespace MongoDB.Driver.GeoJsonObjectModel { [BsonSerializer(typeof(GeoJson2DGeographicCoordinatesSerializer))] public class GeoJson2DGeographicCoordinates : GeoJsonCoordinates