MongoDB 避坑小知识
MongoDB的使用入门这里不多做介绍,可以参考官网学习。学习连接:https://mongodb.github.io/mongo-csharp-driver/2.12/getting_started/
一.自带的_id问题,读取自定义实体时报错: Element '_id' does not match any field or property of class
MongoDB自带会生成一个_id,类似MySQL、SQLServer等关系数据中的主键,它是一种特别的数据格式。
解决方案:1.使用[BsonIgnoreExtraElements]特性。
为避免每个实体都需要重复操作,我们可以新建一个BaseEntity,然后加上[BsonIgnoreExtraElements(Inherited = true)],这里需要注意,需要指示子类集成Inherited=rue,这是C#里Attribute的一个属性,可使子类继承父类的Attribute
2.添加 _id即可
你的代码看起来可能是这样的:
//注意这是两种解决方案,选任意一种即可 [MongoDB.Bson.Serialization.Attributes.BsonIgnoreExtraElements(Inherited = true)]//方法1 public class BaseEntity { //方法2 //public MongoDB.Bson.ObjectId _id { get; set; } }
3.全局添加:MongoDB.Bson.Serialization.Conventions.ConventionRegistry.Register("IgnoreExtraElements", new MongoDB.Bson.Serialization.Conventions.ConventionPack { new MongoDB.Bson.Serialization.Conventions.IgnoreExtraElementsConvention(true) }, type => true);
二.存取时间不一样
这个问题是因为MongoDB默认会把时间格式转换为0时区时间,我们时间Datetime时是本地时间,也就是东八区时间。
1.你可以使用下列这样操作来转换,需要注意,此方法只是帮在显示时转换了一下,数据存储的数据还是0时区的。
[MongoDB.Bson.Serialization.Attributes.BsonDateTimeOptions(Kind = DateTimeKind.Local)] public DateTime CreatedTime { get; set; }
2.全局添加,找一个合适的位置添加一下代码,我是放在静态构造函数内,根据业务自己决定
MongoDB.Bson.Serialization.BsonSerializer.RegisterSerializer(typeof(DateTime),
new MongoDB.Bson.Serialization.Serializers.DateTimeSerializer(DateTimeKind.Local, MongoDB.Bson.BsonType.DateTime));