Reputation: 179
Here is the sample data from a collection. Basically the only thing that I am trying to do is read all of the data like this in as a "Student" but it is throwing an error for some reason. It works fine when I read them all in as Bson documents but that is not what I want to do. Here is the error:
An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
Additional information: One or more errors occurred.
what am I doing wrong?
{ "_id" : 137, "name" : "Tamika Schildgen", "scores" : [ { "type" : "exam", "score" : 4.433956226109692 }, { "type" : "quiz", "score" : 65.50313785402548 }, { "type" : "homework", "score" : 89.5950384993947 } ] }
static async Task MainAsync(string[] args)
{
var client = new MongoClient();
var db = client.GetDatabase("school");
var col = db.GetCollection<Student>("students");
var list = await col.Find(new BsonDocument())
.ToListAsync();
foreach(var doc in list)
{
Console.WriteLine(doc);
}
}
}
class Student
{
public ObjectId Id { get; set; }
public string name { get; set; }
public Scores[] scores { get; set; }
}
class Scores
{
public string type { get; set; }
public double score { get; set; }
}
Upvotes: 0
Views: 1170
Reputation: 81
The error lies in Id field type:
If you turn on the option of breaking execution when a CLR exception is thrown (Menu Debug|Exceptions), you will see a message similar to: "An error occurred while deserializing the Id property of class ConsoleApplication2.Student: Cannot deserialize a 'ObjectId' from BsonType 'Double'."
If you change the class Student to:
public class Student
{
public int Id { get; set; }
public string name { get; set; }
public Scores[] scores { get; set; }
}
the exception will not be thrown anymore.
(Additionally, to get readable results, you should probably override ToString() method for Student class).
Upvotes: 1