Click here to Skip to main content
15,885,141 members
Articles / Web Development / ASP.NET

Solve Mongo DB Element Does Not Match Any Field or Property of Class

Rate me:
Please Sign up or sign in to vote.
4.20/5 (6 votes)
15 Mar 2015CPOL 43.5K   4   1
Solve Mongo DB Element does not match any field or property of class

Introduction

Due to non schema nature of mongodb collection, one collection may contain a distinct number of fields. It's not recommended though, it's possible to contain different number of fields due to business requirements. So for example, say we have a collection “Client”, under which there are 2 documents. The second document lacks 1 field “City”. So while binding back to POCO via C# driver, we get an exception “Element does not match any field or property of class”.

sample-1

Solution

When a BSON document is deserialized back to POCO, the name of each element is used to look up a matching field or property in the class map, when deserializer does not find the mapping property it throws an exception, that we have in this scenario. If we want to ignore those extra properties, there are two possible ways, during deserialization or during initialization of the BsonClassMap. I prefer this while I do the mapping, I live to keep my POCO clean.

sample-2

As you can see, the above code block, SetIgnoreExtraElements methods is used to specify inside mapping to ignore extra elements from BSON document.

map.SetIgnoreExtraElements(true);

That’s it, now you can work with your POCO more easily.


Image 3 Image 4

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Chief Technology Officer
Bangladesh Bangladesh
I am a Software Engineer and Microsoft .NET technology enthusiast. Professionally I worked on several business domains and on diverse platforms. I love to learn and share new .net technology and my experience I gather in my engineering career. You can find me from here

Personal Site
Personal Blog
FB MS enthusiasts group
About Me

Comments and Discussions

 
QuestionInheritence issue Pin
Hassan F.29-Apr-17 9:49
professionalHassan F.29-Apr-17 9:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.