CS Lewis
CS Lewis

Reputation: 489

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

All:

I have IEnumerable called ObjectsList which basically contains a bunch of MongoDB.Bson.ObjectId objects. I need to cast the entire IEnumerable called ObjectsList into an IEnumerable called 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 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 that will cast the aforementioned IEnumerable?

Upvotes: 1

Views: 11586

Answers (2)

Marian Kosaniak
Marian Kosaniak

Reputation: 191

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

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

Upvotes: 2

sheilak
sheilak

Reputation: 5873

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

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

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

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

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

Upvotes: 2

Related Questions