7

With C# 6 I can write:

public class Person
{
    public Guid Id { get; }
    public string Name { get; }
    public Person(Guid id, string name)
    {
        Id = id;
        Name = name;
    }
}

Unfortunately a class like this is not serialized correctly by MongoDb driver, properties are not serialized.

MongoDb only serialize by default properties with getter and setter. I known that you can manually change the class mapping and tell serializer to include get-only properties but I was looking for a generic way to avoid customizing each mapping.

I was thinking to create a custom convention similar to ReadWriteMemberFinderConvention but without the CanWrite check.

There are other solutions? Constructor will be called automatically or I need some other customization?

Davide Icardi
  • 11,919
  • 8
  • 56
  • 77

5 Answers5

8

UPDATE: MongoDB.Bson version 2.10 now comes with an ImmutableTypeClassMapConvention


I have tried to solve this problem by creating a convention that map all read only properties that match a constructor and also the matched constructor.

Assume that you have an immutable class like:

public class Person
{
    public string FirstName { get; }
    public string LastName { get; }
    public string FullName => FirstName + LastName;
    public ImmutablePocoSample(string lastName)
    {
        LastName = lastName;
    }

    public ImmutablePocoSample(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

Here is the code of the convention:

using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Conventions;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

/// <summary>
/// A convention that map all read only properties for which a matching constructor is found.
/// Also matching constructors are mapped.
/// </summary>
public class ImmutablePocoConvention : ConventionBase, IClassMapConvention
{
    private readonly BindingFlags _bindingFlags;

    public ImmutablePocoConvention()
            : this(BindingFlags.Instance | BindingFlags.Public)
    { }

    public ImmutablePocoConvention(BindingFlags bindingFlags)
    {
        _bindingFlags = bindingFlags | BindingFlags.DeclaredOnly;
    }

    public void Apply(BsonClassMap classMap)
    {
        var readOnlyProperties = classMap.ClassType.GetTypeInfo()
            .GetProperties(_bindingFlags)
            .Where(p => IsReadOnlyProperty(classMap, p))
            .ToList();

        foreach (var constructor in classMap.ClassType.GetConstructors())
        {
            // If we found a matching constructor then we map it and all the readonly properties
            var matchProperties = GetMatchingProperties(constructor, readOnlyProperties);
            if (matchProperties.Any())
            {
                // Map constructor
                classMap.MapConstructor(constructor);

                // Map properties
                foreach (var p in matchProperties)
                    classMap.MapMember(p);
            }
        }
    }

    private static List<PropertyInfo> GetMatchingProperties(ConstructorInfo constructor, List<PropertyInfo> properties)
    {
        var matchProperties = new List<PropertyInfo>();

        var ctorParameters = constructor.GetParameters();
        foreach (var ctorParameter in ctorParameters)
        {
            var matchProperty = properties.FirstOrDefault(p => ParameterMatchProperty(ctorParameter, p));
            if (matchProperty == null)
                return new List<PropertyInfo>();

            matchProperties.Add(matchProperty);
        }

        return matchProperties;
    }


    private static bool ParameterMatchProperty(ParameterInfo parameter, PropertyInfo property)
    {
        return string.Equals(property.Name, parameter.Name, System.StringComparison.InvariantCultureIgnoreCase)
               && parameter.ParameterType == property.PropertyType;
    }

    private static bool IsReadOnlyProperty(BsonClassMap classMap, PropertyInfo propertyInfo)
    {
        // we can't read 
        if (!propertyInfo.CanRead)
            return false;

        // we can write (already handled by the default convention...)
        if (propertyInfo.CanWrite)
            return false;

        // skip indexers
        if (propertyInfo.GetIndexParameters().Length != 0)
            return false;

        // skip overridden properties (they are already included by the base class)
        var getMethodInfo = propertyInfo.GetMethod;
        if (getMethodInfo.IsVirtual && getMethodInfo.GetBaseDefinition().DeclaringType != classMap.ClassType)
            return false;

        return true;
    }
}

You can register i using:

ConventionRegistry.Register(
    nameof(ImmutablePocoConvention),
    new ConventionPack { new ImmutablePocoConvention() },
    _ => true);
Davide Icardi
  • 11,919
  • 8
  • 56
  • 77
  • 2
    MongoDB.Bson version 2.10 now comes with an ImmutableTypeClassMapConvention that works on the same principle. It need truly immutable types, though, so no public setters allowed. – adhominem Mar 25 '20 at 09:24
4

I had the same problem and found the accepted answer to be overly complex.

Instead, you can simply add the BsonRepresentation attribute to the read-only property that you want serialized:

public class Person
{
    public string FirstName { get; }

    public string LastName { get; }

    [BsonRepresentation(BsonType.String)]
    public string FullName => $"{FirstName} {LastName}";
}
skyzaDev
  • 108
  • 8
  • It depends on the case. If you have some 3rd party library objects with readonly properties you can not simply use attributes, therefore Davides answer is more universal. – hbertsch Dec 02 '22 at 15:18
3

If you don't want all the read-only properties to be serialized you can add a public set doing nothing (if applicable), just note that the property will be re-evaluated when your class is de-serialized.

public class Person
{
    public string FirstName { get; }
    public string LastName { get; }
    public string FullName
    {
        get
        {
            return FirstName + LastName;
        }
        [Obsolete("Reminder to not use set method")]
        internal set
        {
           //this will switch on the serialization
        }
    }
}
Tono Nam
  • 34,064
  • 78
  • 298
  • 470
ghiso
  • 73
  • 7
2

Assume that you have an immutable class like:

public class Person
{
    public string FirstName { get; }

    public string LastName { get; }

    [BsonRepresentation(BsonType.String)]
    public string FullName => $"{FirstName} {LastName}";
}

Just add [BsonElement] resulting

public class Person
{
    [BsonElement]
    public string FirstName { get; }

    [BsonElement]
    public string LastName { get; }

    public string FullName => $"{FirstName} {LastName}";
}
0

This is a simplification of the post above registering a convention.

this convention should be created

public class ReadOnlyMemberFinderConvention : ConventionBase, IClassMapConvention
{
    public void Apply(BsonClassMap classMap)
    {
        var readOnlyProperties = classMap.ClassType.GetTypeInfo()
            .GetProperties()
            .Where(p => p.CanRead && !p.CanWrite)
            .ToList();
        
        readOnlyProperties.ForEach(p => classMap.MapProperty(p.Name));
    }
}

and then registered

ConventionRegistry.Register(
            "ReadOnlyMemberFinderConvention",
            new ConventionPack { new ReadOnlyMemberFinderConvention() },
            _ => true);
Gemu
  • 409
  • 4
  • 4