Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element 'Id' does not match any field or property of class

I got the result from the collection in MongoDB, the structure is the same as below

[DataContract] public class Father {     [BsonId]     [DataMember]     public MongoDB.Bson.ObjectId _id { get; set; }      [DataMember]     public string Id { get; set; }      [DataMember]     public List<Child> childs { get; set; } }  [DataContract] public class Child {     [DataMember]     public string Id { get; set; }      [DataMember]     public int Name { get; set; } } 

When I try this:

List<Father> f = result.ToList(); 

It calls Element 'Id' does not match any field or property of the class Model.Child

I think it just takes 'Id' as something else.

How can I deal with it? Thank you

like image 886
EasonBlack Avatar asked Jul 19 '12 09:07

EasonBlack


2 Answers

You can resolve the issue by adding [BsonIgnoreExtraElements] on top of the class declaration. ObjectId is internally maintained by MongoDB which may not be needed unless you want to get additional information such as timestamp from the object. Hope this helps.

like image 190
Naga Avatar answered Sep 21 '22 19:09

Naga


var conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };         ConventionRegistry.Register("IgnoreExtraElements", conventionPack, type => true); 

This works just perfectly! [BsonIgnoreExtraElements] also worked well, but, if you want to add any other ConventionRegistry like CamelCaseElementNameConvention, then, it overrides the Attribute one and the same exception occurs. Not sure if that could also be achieved using some other attribute.

like image 40
Abhilash Pokhriyal Avatar answered Sep 20 '22 19:09

Abhilash Pokhriyal