Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue

Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue

Questions : Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue

390

All:

I have IEnumerable called ObjectsList which in4codes_mongodb basically contains a bunch of in4codes_mongodb MongoDB.Bson.ObjectId objects. I need to in4codes_mongodb cast the entire IEnumerable called in4codes_mongodb ObjectsList into an IEnumerable called in4codes_mongodb 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>(); 

Unfortunately, the casting gives the in4codes_mongodb following error:

Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue System.SystemException {System.InvalidCastException} 

Could someone please show the proper code in4codes_mongodb that will cast the aforementioned in4codes_mongodb IEnumerable?

Total Answers 2
31

Answers 1 : of Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue

In general if you want to cast a list of in4codes_casting ObjectIds to BsonValues, you need to do in4codes_casting a project and explicit cast like this:

ObjectsList.Select(v => (BsonValue)v).ToList(); 

I believe it’s due to the reasons in4codes_casting explained in the answers to this in4codes_casting question.

In your case where you have a list of in4codes_casting Objects rather than ObjectIds, I found in4codes_casting you need to put in an additional cast to in4codes_casting ObjectId – otherwise you get the same in4codes_casting error as with the code you’ve tried.

ObjectsList.Select(v => (BsonValue)(ObjectId)v).ToList(); 

0

1

Answers 2 : of Unable to cast object of type MongoDB.Bson.ObjectId to type MongoDB.Bson.BsonValue

I have this error once I migrate to .net in4codes_casting core. Old Project using Newtonsoft.Json in4codes_casting and new .net core using in4codes_casting System.Text.Json.Serialization. You can in4codes_casting use one of them or add both [JosnIgnore] in4codes_casting attributes.

[JsonIgnore] [System.Text.Json.Serialization.JsonIgnore] //add this one [BsonIgnoreIfNull] [BsonId] [Ignore] public BsonValue ID { get; set; } 

0