[CSHARP-576] MongoDB BsonDocument Down-Casting Created: 21/Sep/12 Updated: 05/Apr/19 Resolved: 24/Sep/12 |
|
| Status: | Closed |
| Project: | C# Driver |
| Component/s: | None |
| Affects Version/s: | 1.6 |
| Fix Version/s: | None |
| Type: | Task | Priority: | Major - P3 |
| Reporter: | Nir Pinhasov | Assignee: | Robert Stam |
| Resolution: | Done | Votes: | 0 |
| Labels: | question | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Description |
|
I have a collection in MongoDB which I'm trying to "FindAndModify" using C# driver. This collection holds types of a base class and its derived classed, as follows: [BsonDiscriminator(RootClass = true)] } public class Son : Father { public string SomeProperty { get; private set; } } When I'm trying to cast the BsonDocument to my base class, after the FindAndModify, where the result is "Son": Father modifiedDocument = result.GetModifiedDocumentAs<Father>(); I get the following exception: System.IO.FileFormatException: Element 'SomeProperty' does not match any field or property of class Father. Any idea why? -Can't I perform a down cast here? Thanks, |
| Comments |
| Comment by Robert Stam [ 22/Sep/12 ] | |||||||
|
You could also use the BsonKnownTypes attribute on the Father class:
The trick is that the driver must somehow or another "know" about the Son class before you can deserialize an instance of it. | |||||||
| Comment by Nir Pinhasov [ 22/Sep/12 ] | |||||||
|
I was able to solve this issue by registering the class map of the "Son" type on load. Here's a reference to the code I'm using: if (!BsonClassMap.IsClassMapRegistered(typeof(T))) ); So now I'm using this for all my stored objects on load. So, thanks! |