[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 Father
{
public Guid Id

{ get; private set; }
}

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,
Nir.



 Comments   
Comment by Robert Stam [ 22/Sep/12 ]

You could also use the BsonKnownTypes attribute on the Father class:

 
[BsonDiscriminator(RootClass = true)]
[BsonKnownTypes(typeof(Son))]
public class Father
{
    public Guid Id { get; private set; }
}

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)))
{
BsonClassMap.RegisterClassMap<T>
(cm =>

{ cm.AutoMap(); }

);
}

So now I'm using this for all my stored objects on load.
I got this to work when noticed the last post of Robert, here:
https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/LTkfPshnh9o

So, thanks!

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