在寻找解决方案时我得到了this https://stackoverflow.com/questions/30421379/mongodb-custom-collection-serializer and this http://mongodb.github.io/mongo-csharp-driver/2.0/reference/bson/mapping/但这个概念对我来说并不清楚,所以无法实现它:(。
当我尝试更新数据库中的值(特别是日期时间对象)时,会发生此错误。下面是我正在使用的代码:-
var update = Builders<Model>.Update
.Set(t => t.startdate, BsonValue(objModel.startdate));
var result = model.UpdateOne(query, update);
BonValue 函数如下:-
private static BsonValue BsonValue(object obj)
{
if (obj == null)
return (BsonValue)obj ?? BsonNull.Value;
else if (obj.GetType() == typeof(string))
return new BsonString(obj.ToString());
else if (obj.GetType() == typeof(DateTime))
return new BsonDateTime(DateTime.SpecifyKind(DateTime.Parse(obj.ToString()), DateTimeKind.Utc));
else if (obj.GetType() == typeof(int))
return new BsonInt32(int.Parse(obj.ToString()));
else
return (BsonValue)obj;
}
我认为这是因为我已经开始使用 mongoDB.Bson 和 mongoDB.Driver 的升级包。当前版本是2.3.0
任何帮助将不胜感激。
Edit
1)在插入数据时我所做的如下:-
BsonDocument objBsonDoc = new BsonDocument {
{ "startdate",DataManager.GetBsonValue( objModel.startdate) }
}; return dbHelper.CreateDocument(Model.CollectionName, objBsonDoc);
在 objBsonDoc 中,我可以看到 StartDate 值,但在 CreateDocument 命令之后 StartDate 不会保存在数据库中。
2)这就是我在更新值时所做的事情:-
public static long Edit(Model objModel, string id)
{
IMongoCollection<Model> model = dbHelper.GetCollection<Model>(Model.CollectionName);
var query = Builders<Model>.Filter.Eq(t => t.id, ObjectId.Parse(id));
var update = Builders<Model>.Update
.Set(t => t.startdate, objModel.startdate);
var result = model.UpdateOne(query, update);
return result.MatchedCount;
}
在这里我还获得了开始日期的值,并且还获得了modifiedcount=1,但是当我检查数据库时,它仍然显示开始状态为空。
我的模特班:-
public class Model
{
public static string CollectionName
{
get { return "Collection"; }
}
public ObjectId id { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
[BsonRepresentation(BsonType.DateTime)]
public DateTime startdate { get; set; }
}