[CSHARP-3160] Cannot hide base property Created: 13/Jul/20  Updated: 27/Oct/23  Resolved: 13/Jul/20

Status: Closed
Project: C# Driver
Component/s: BSON, Json.NET
Affects Version/s: None
Fix Version/s: None

Type: Bug Priority: Major - P3
Reporter: Luca Bellavia Assignee: Robert Stam
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Net Core 3.1



 Description   

Hi everyone,

I'm currently stuck in this situation:

class A
{
    public DateTime CreatedOn \{ get; set; }
}
 
class B : A
{ 
    public new DateTimeOffset CreatedOn \{ get; set; }
}

Every time I try to get an IMongoCollection<B> I get this error:

MongoDB.Bson.BsonSerializationException: 'The property 'CreatedOn' of type 'B' cannot use element name 'CreatedOn' because it is already being used by property 'CreatedOn' of type 'A`1.

Is there any way to get around this problem?

Thank you in advance,

Luca



 Comments   
Comment by Robert Stam [ 13/Jul/20 ]

The C# driver has some conventions that it uses to map a C# class to a BSON document representation.

One of the assumptions these conventions make is that subclasses won't hide existing properties as your example does.

If you must hide an existing property you would have to write your own custom serializer (at least for class B in your example). You will have to decide how to serialize an instance of B and how to resolve the conflict between the two classes using the same property name with a different type.

If you can change the name of the new property in class B to not conflict with any existing properties in the base class that is the easiest solution.

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