无法将类型 MongoDB.Bson.ObjectId 的对象转换为类型 MongoDB.Bson.BsonValue
Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue
全部:
我有一个名为 ObjectsList 的 IEnumerable,它基本上包含一堆 MongoDB.Bson.ObjectId 个对象。我需要将整个 IEnumerable 称为 ObjectsList 转换为一个 IEnumerable 称为 BsonValueList
IEnumerable<Object> ObjectsList = DBConnection.database.GetCollection<ELLCsLog>("FMS_TM_MST_Logs")
.FindOneByIdAs<ELLCsInterfaceLog>(ObjectId.Parse(logIdArg.ToString())).logEventsIdList;
IEnumerable<BsonValue> BsonValueList = ObjectsList.Cast<BsonValue>();
不幸的是,转换给出了以下错误:
Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue System.SystemException {System.InvalidCastException}
有人可以显示将转换上述 IEnumerable 的正确代码吗?
一般来说,如果您想将 ObjectId 列表转换为 BsonValues,您需要像这样进行项目和显式转换:
ObjectsList.Select(v => (BsonValue)v).ToList();
我相信这是由于解释的原因 in the answers to this question。
如果你有一个对象列表而不是 ObjectId,我发现你需要对 ObjectId 进行额外的转换 - 否则你会得到与你尝试过的代码相同的错误。
ObjectsList.Select(v => (BsonValue)(ObjectId)v).ToList();
迁移到 .net Core 后出现此错误。旧项目 using Newtonsoft.Json
和新 .net 核心 using System.Text.Json.Serialization
。您可以使用其中之一或添加两个 [JosnIgnore]
属性。
[JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore] //add this one
[BsonIgnoreIfNull]
[BsonId]
[Ignore]
public BsonValue ID { get; set; }
全部:
我有一个名为 ObjectsList 的 IEnumerable,它基本上包含一堆 MongoDB.Bson.ObjectId 个对象。我需要将整个 IEnumerable 称为 ObjectsList 转换为一个 IEnumerable 称为 BsonValueList
IEnumerable<Object> ObjectsList = DBConnection.database.GetCollection<ELLCsLog>("FMS_TM_MST_Logs")
.FindOneByIdAs<ELLCsInterfaceLog>(ObjectId.Parse(logIdArg.ToString())).logEventsIdList;
IEnumerable<BsonValue> BsonValueList = ObjectsList.Cast<BsonValue>();
不幸的是,转换给出了以下错误:
Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue System.SystemException {System.InvalidCastException}
有人可以显示将转换上述 IEnumerable 的正确代码吗?
一般来说,如果您想将 ObjectId 列表转换为 BsonValues,您需要像这样进行项目和显式转换:
ObjectsList.Select(v => (BsonValue)v).ToList();
我相信这是由于解释的原因 in the answers to this question。
如果你有一个对象列表而不是 ObjectId,我发现你需要对 ObjectId 进行额外的转换 - 否则你会得到与你尝试过的代码相同的错误。
ObjectsList.Select(v => (BsonValue)(ObjectId)v).ToList();
迁移到 .net Core 后出现此错误。旧项目 using Newtonsoft.Json
和新 .net 核心 using System.Text.Json.Serialization
。您可以使用其中之一或添加两个 [JosnIgnore]
属性。
[JsonIgnore]
[System.Text.Json.Serialization.JsonIgnore] //add this one
[BsonIgnoreIfNull]
[BsonId]
[Ignore]
public BsonValue ID { get; set; }