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?
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.
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:
Here is the code of the convention:
You can register i using: