Search code examples
c#mongodbcastingbsonobjectid

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?


Solution

  • 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();