[CSHARP-681] need a different way to accomplish BsonIgnoreExtraElements Created: 14/Feb/13  Updated: 19/Dec/20  Resolved: 14/Feb/13

Status: Closed
Project: C# Driver
Component/s: Feature Request
Affects Version/s: 1.7
Fix Version/s: None

Type: New Feature Priority: Major - P3
Reporter: Travis Laborde Assignee: Unassigned
Resolution: Done Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

any


Issue Links:
Related
related to CSHARP-1478 BsonClassMap.Reset() is not consisten... Closed

 Description   

If there are documents in Mongo, and the C# driver tries to create them into .NET classes that have "not enough" properties, the c# driver currently throws an exception. This is a problem in many cases.

Someone has asked for this before, but was told that this was "by design" and that using the [BsonIgnoreExtraElements] attribute on the .NET class would solve the problem. It does, BUT.....

I find this solution to be distasteful in the extreme because it ties the c# object model to Mongo. The model must have a dependency on the mongo dll that contains the attribute. This effectively prevents me from being able to use that attribute at all.

Which means that migrating data is extremely painful when it involves removing properties from the model that have already been saved in Mongo.

It would be MUCH better, if at the driver level, in the code, I could say something like:

database.GetCollectionIgnoringExtraElements
or
collection.IgnoreExtraElementsWhenDeserializing
or
whatever.YouGetTheIdea()

The whole point being - some way other than by adding a dependency on my model to Mongo, to achieve this goal. It would make migrations to the model MUCH EASIER. And would allow us to continue our adoption of Mongo.



 Comments   
Comment by Travis Laborde [ 15/Feb/13 ]

Awesome - thanks!

Comment by Robert Stam [ 14/Feb/13 ]

There is already a way to do this that doesn't require your POCOs to depend on the MongoDB driver.

Somewhere in your application startup (in a part of the application that does already depend on the MongoDB driver) call this:

BsonClassMap.RegisterClassMap<C>(cm => { cm.AutoMap(); cm.SetIgnoreExtraElements(true); });

For every option you might want to configure, the following document shows how to do it either with attributes or with code:

http://docs.mongodb.org/ecosystem/tutorial/serialize-documents-with-the-csharp-driver/

Here's a quote from that document: "attributes are very convenient to use but for those who prefer to keep serialization details out of their domain classes be assured that anything that can be done with attributes can also be done without them".

Generated at Wed Feb 07 21:37:32 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.