MongoDB C# Driver ignore property on serialization if the getter is inaccessible

时间:2018-09-19 08:20:50

标签: c# mongodb serialization properties

I need to save/serialize a class where some of the properties might have getters, that could be inaccessible at runtime. In my special case these are ECS(Entity-Component-System)-Entities, which are getting composed at runtime and therefore not any Component-Properties are all available at runtime. If you don't know what ECS does, just read on, it does not matter for the issue here. If you're interested to know what ECS is, just have a look here: ECS Wikipedia

for example have an Entity class like this:

public class MyEntity
{
    public PersonComponent person{get;set}
    public bool hasPersonComponent{get;}
    public AdressComponent adress{get;set;}
    public bool hasAdressComponent{get;}
}

So it contains two Components and a bool property for each Component, that returns true, if these Component even exists at runtime.

And a classmap for serializing these entities

BsonClassMap.RegisterClassMap<MyEntity>(cm =>
        {
            cm.AutoMap();
            cm.MapMember(c => c.person);
            cm.MapMember(c => c.adress);
        });

MongoDB is currently serializing these Entity class only, if all of the mapped properties are existing at runtime, so that all their Getters are accessible. If one of them is missing, MongoDB is not serialzing the whole class and it is getting not saved into the DB.

Is there a way to ignore these properties on serialization/saving of this class?

I found already, that this could be done via Conventions and also found a SetShouldSerializeMethod, but I can't find a syntax to set the SetShouldSerializeMethod for setting the serialization of the regarding member/property to false by a given hasComponent == false bool value, which is another property of the same class.

So pseudo code would be:

if(!myEntity.hasPersonComponent) cm.MapMember(c => c.person).SetShouldSerialize(false);
if(!myEntity.hasAdressComponent) cm.MapMember(c => c.adress)SetShouldSerialize(false);

but thats defintiely not the correct syntax. I'd also would prefer to save all these conventions in a so called ConventionsPack class, but can't find any examples for creating this.

Thank you in advance for your help!

0 个答案:

没有答案