MongoDB在反序列化属性时抛出异常''System.IO.FileFormatException''

时间:2015-04-24 05:37:21

标签: c# mongodb mongodb-.net-driver

型号:

    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; }
    }

问题收集在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"
  }
 ]
}

获取问题方法:

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);
 }
}

当我尝试检索问题时,我得到以下异常:

  

发生了'System.IO.FileFormatException'类型的异常   MyProj.dll但未在用户代码中处理

     

其他信息:反序列化时发生错误   类Data.QuestionModel的PreRenderedQuestionsList属性:   元素'Id'与类

的任何字段或属性都不匹配

我可以添加和更新问题集,但无法检索数据。我缺少什么?

2 个答案:

答案 0 :(得分:1)

这是&#34; Id&#34;导致问题的子文档arraylist中的字段。这是一个保留字,因此也是这种行为。使用[BsonNoId]明确标记您的子文档模型,您的查找应该按预期工作。

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

答案 1 :(得分:0)

基本上,当类中的属性标题为“Id”时会发生错误。在您的情况下,我建议您将名称更改为“PreRenderedQuestion”类中的“Id”属性。这对我有用。