BsonSerializationException when inheriting from Domain Object Class

I have a Domain Library with a User Class. This class should not have any dependencies.

public abstract class UserEntity 
        public virtual string Id { get; set; } = string.Empty;
        public string FirstName { get; set; } = string.Empty;
        public string LastName { get; set; } = string.Empty;

In my Infrastructure Library (seperate project), I have a User Dto Class that inherits from “UserEntity”. This library has the MongoDB Drivers.

public class UserDto : UserEntity
    public override string Id { get; set; } = string.Empty;

What I’m trying to do is to make the “Id” property to be the Id for the Bson Object. I’m using Class inheritance to avoid mapping if possible. It was setup in this matter so I could use another Class Object that inherits “UserEntity” if I wanted to support another database.

The error message is below. What am I doing wrong or what can I do to get around this?


Hi, @Derek_Welton,

Welcome to the MongoDB Community Forums.

I understand that you’re trying to override the BSON representation of a field in a derived class. This is not something that the driver supports.

You have two options…

Option 1: The [BsonRepresentation] attribute is simply metadata and will be ignored by other frameworks. So just decorate your base classes with the needed BSON attributes. The MongoDB .NET/C# Driver will use these attributes, everything else will ignore them.

Option 2: If you don’t want to decorate / pollute your base classes with MongoDB-specific attributes, you can register the class maps explicitly configuring your MongoDB serialization through code. The following class map configuration for UserEntity results in similar behaviour as applying the attributes:

BsonClassMap.RegisterClassMap<UserEntity>(cm =>
        cm.GetMemberMap(x => x.Id)
          .SetSerializer(new StringSerializer(BsonType.ObjectId));

Note that your default value for Id would have to be null because an empty string isn’t a valid ObjectId.

There is more information on serialization and mapping in our documentation.


1 Like

Hey James,

Thanks again for your response. I for some reason did not know you supported Class Mapping as you shown above. Thank you for sharing this information with me. Thanks for also clarifying that the attributes from the BSON library doesn’t effect other parts of the class.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.