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

EasonBlack picture EasonBlack · Jul 19, 2012 · Viewed 32.4k times · Source

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

Answer

Naga picture Naga · Mar 15, 2019

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.