Unable to cast object of type 'MongoDB.Bson.Serializatio
本文关键字:MongoDB Bson Serializatio type to cast object of Unable | 更新日期: 2023-09-27 18:14:28
在寻找解决方案时,我得到了这个和这个,但这个概念对我来说并不清楚,所以无法实现它。当我尝试更新数据库中的值(特别是datetime对象)时,会发生此错误。下面是我使用的代码:-
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
任何帮助都将非常感激。
编辑
1)插入数据时,我所做的如下:-
BsonDocument objBsonDoc = new BsonDocument {
{ "startdate",DataManager.GetBsonValue( objModel.startdate) }
}; return dbHelper.CreateDocument(Model.CollectionName, objBsonDoc);
在objBsonDoc中,我可以看到StartDate值,但在CreateDocument命令后,StartDate没有保存在DB中。
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,但当我检查DB时,它仍然显示为空。
My Model class:-
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; }
}
你不需要按照你自己的方式进行转换。
尝试在你的模型上设置BsonRepresentation
public class Model
{
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
[BsonRepresentation(BsonType.DateTime)]
public DateTime startDate { get; set; }
}
为了澄清,我可以建议您将您的集合变量重命名为集合而不是模型,因为这会引起混淆,所以
IMongoCollection<Model> collection = dbHelper.GetCollection<Model>(Model.CollectionName);
Model objModel = new Model { startDate = DateTime.UtcNow };
collection.InsertOne(yourModel);
要执行更新,你不需要设置为BsonValue
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);
一个建议,是将您的ObjectId存储为字符串,并使用BsonRepresentation与DateTime:
[BsonRepresentation(BsonType.ObjectId)]
[BsonId]
public string Id { get; set; }
这样你就不需要把它解析成ObjectId它的工作原理是一样的,所以你的过滤器变成了
var query = Builders<Model>.Filter.Eq(t => t.Id, id);
或者你可以在你的更新中直接使用Lambda,像这样:
var update = Builders<Model>.Update
.Set(t => t.Id == id, objModel.startdate);