1
votes

Model:

    public class QuestionModel
    {
     [BsonId]
     [BsonRepresentation(BsonType.ObjectId)]
     public string Id { get; set; }
     public string Name { get; set; }
     public string Expression { get; set; }
     [BsonIgnoreIfNull]
     public List<PreRenderedQuestion> PreRenderedQuestionsList { get; set; } 
    }

    public class PreRenderedQuestion
    {
     public string Id { get; set; }
     public string Name { get; set; }
     public string Expression { get; set; }
     public string ExpressionWithValues { get; set; }
    }

Question Collection In DB:

{
 "_id" : ObjectId("5539b948bb63bc0680f29025"),
 "Name" : "addition",
 "Expression " : "a+b",
 "PreRenderedQuestionsList" : [ 
  {
   "Id" : "5539b948bb63bc0680f29325",
   "Name" : "addition",
   "Expression " : "a+b",
   "ExpressionWithValues " : "5+2"
  },
  {
   "Id" : "5539b948bb63bc0680f29326",
   "Name" : "addition",
   "Expression " : "a+b",
   "ExpressionWithValues " : "6+9"
  }
 ]
}

Get Question Method:

function getQuestions(QuestionModel oModel)
{
 _query = Query<QuestionModel>.Where(e => e.Is_Deleted == false);
  _cursor = _collection.Find(_query);
 oModel.QuestionList = new List<QuestionModel>();
 foreach (QuestionModel ques in _cursor)
 {
   oModel.QuestionList.Add(ques);
 }
}

When I try to retrieve question, I get following exception:

An exception of type 'System.IO.FileFormatException' occurred in MyProj.dll but was not handled in user code

Additional information: An error occurred while deserializing the PreRenderedQuestionsList property of class Data.QuestionModel: Element 'Id' does not match any field or property of class

I am able to add and update Question Collection, but not able to retrieve data. What I am missing?

2
Try adding [BsonElement("Id")] to it. - CodesInChaos
Your Id is a string while you say it's BsonType.ObjectId. You should probably use ObjectId instead... - i3arnon
Actually, that shouldn't happen, at least not with the 2.0 driver - which driver version are you using? - mnemosyn

2 Answers

1
votes

It is "Id" field inside your subdocument arraylist that is causing the issue. This is a reserved word and hence this behaviour. Mark your subdocument model with [BsonNoId] explicitly and your find should work as intended.

[BsonNoId] public class PreRenderedQuestion { .... }

0
votes

Basically the error occurs when a property in the class is titled "Id". In your case I suggest that you change the name to the "Id" property in "PreRenderedQuestion" class. This worked for me.