Search code examples
c#mongodb.net-coremongodb-.net-driver

How to set a MongoDb Serializer to an inner object property


Is it possible for MongoDb to set a DateTimeSerializer for a C# inner object DataTime property in a POCO class using ClassMap without the BsonDateTimeOptions attribute ?

Example :

public class Entity
{
    public string Id { get; init; }
    
    public string Currency { get; init; }
    
    public IEnumerable<InnerEtity> InnerEtities { get; init;}
}
        
public class InnerEtity
{
    //Don't want to use this attribute
    [BsonDateTimeOptions(DateOnly = true)]
    public DateTime Date { get; set; }
        
    public double Value { get; set; }
}

Solution

  • You can use "imperative" mapping instead of using the attributes, e.g.

    BsonClassMap.RegisterClassMap<InnerEtity>(classMap =>
    {
        classMap.AutoMap();
        classMap.GetMemberMap(c => c.Date).SetSerializer(new DateTimeSerializer(dateOnly: true));
    });
    

    This way, you do not need to use attributes for the mapping and keep the class "MongoDB-agnostic". Please be aware that you need to run the code when bootstraping your application so that MongoDB C# Driver already knows the class map when using the entity for the first time.