So, I am performing a SelectMany query to iterate through the Lists inside of objects in a collection. Here is my query:
var collection = _database.GetCollection<VehicleDataUpload>(VehiclesCollection);
var aggregation = collection.AsQueryable()
.SelectMany(v => v.VehicleEntries)
.Where(i => Convert.ToInt32(i.PostFlashDTCs) > 0)
.ToList();
However, each time I run this I get the following error:
A first chance exception of type 'System.InvalidOperationException' occurred in MongoDB.Driver.dll
I thought the problem had to do with the convert function, so I changed it to:
.Where(i => Convert.ToInt32("1") > 0)
And it still worked fine. My coworker said it might choke on converting a string 0, but when I hardcode in "0", it still works. For some reason, it just can't convert the class field. I have set the field to string and even set a default value for it:
public class VehicleEntry
{
[BsonElement("PostFlashDTCs")]
[BsonDefaultValue("0")]
public String PostFlashDTCs { get; set; }
}
What is the reason why it shows an InvalidFormatException when I read from the object itself?
EDIT
I wrote a quick for loop to iterate through (after dropping the where step) and print if there was a string that couldn't be converted to an integer. Nothing was printed to the console:
foreach (VehicleEntry vehicle in aggregation1)
{
int result;
if (!Int32.TryParse(vehicle.PostFlashDTCs, out result))
{
Console.WriteLine("Bad value!");
}
}
EDIT 2
I restricted my query a bit to pull from a case that only had 12 VehicleEntry elements. I put a debugger afterward (I removed the where case temporarily) and went through all twelve elements and they all had valid numeric strings for the PostFlashDTCs field, so the problem resides in the convert function, not with an invalid string.
EDIT 3
If I'm unable to use Convert.ToInt32 in a LINQ query, why would it work fine when I hardcode the string value? Is the compiler doing something weird to optimize that code? I'm not aware of such optimization, but I suppose it's possible.