我在我的C#MVC应用程序中使用MongoDB Driver 2.3.0并收到此错误:
"无法从BsonType'文档'反序列化'列表'"
在更新后获取数据.
以下是我的代码:
IMongoCollection<Model> objModel = dbHelper.GetCollection<Model>(Model.CollectionName);
var query = Builders<Model>.Filter.And(
Builders<Model>.Filter.Eq("_id", new ObjectId(Id)),
Builders<Model>.Filter.Eq("locations.locationid", objLocation.locationid));
var update = Builders<Model>.Update.Set("locations", objLocation.ToBsonDocument());
var result = objModel.UpdateMany(query, update, new UpdateOptions { IsUpsert = true });
if (objLocation.isdefaultlocation)
{
var lList = (from e in objModel.AsQueryable<Model>()
where e._id == ObjectId.Parse(Id)
select e.locations).FirstOrDefault();
lList.Where(i => i.isdefaultlocation == true && i.locationid != objLocation.locationid).ToList()
.ForEach(s => s.isdefaultlocation = false);
Model onjO = new Model();
onjO.locations = lList;
var query1 = Builders<Model>.Filter.Eq("_id", new ObjectId(Id)); …Run Code Online (Sandbox Code Playgroud) 在寻找解决方案时,我得到了这个和这个,但这个概念对我来说不清楚,所以无法实现它:(。当我尝试更新数据库中的值(特别是日期时间对象)时,会发生此错误。下面是代码我正在使用:-
var update = Builders<Model>.Update
.Set(t => t.startdate, BsonValue(objModel.startdate));
var result = model.UpdateOne(query, update);
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
我认为这是因为我已经开始使用 mongoDB.Bson 和 mongoDB.Driver 的升级包。当前版本是2.3.0
任何帮助将不胜感激。
编辑
1)在插入数据时我所做的如下:-
BsonDocument objBsonDoc = new BsonDocument {
{ "startdate",DataManager.GetBsonValue( objModel.startdate) …Run Code Online (Sandbox Code Playgroud)