1

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?

3
  • 2
    Try adding [BsonElement("Id")] to it. Commented Apr 24, 2015 at 5:51
  • Your Id is a string while you say it's BsonType.ObjectId. You should probably use ObjectId instead... Commented Apr 24, 2015 at 6:02
  • Actually, that shouldn't happen, at least not with the 2.0 driver - which driver version are you using? Commented Apr 24, 2015 at 6:57

2 Answers 2

1

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 { .... }

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.