Gabriele Giuseppini
Gabriele Giuseppini

Reputation: 1581

Protobuf-net RuntimeTypeModel not serializing members of base class

Say I have the following base class:

[DataContract]
[Serializable]
public abstract class DimensionEntity
{
    [DataMember(Order = 1)]
    private readonly Date effectiveDatespan;
    ...
}

And the following derived class:

[DataContract]
[Serializable]
public class ClearingSite : DimensionEntity
{
    [DataMember(Order = 1)]
    private readonly string code;
    ...
}

When I serialize an instance of ClearingSite as follows:

        model.Add(typeof(ClearingSite), true);
        model.Serialize(ms, clearingSite);

I can see that only the code member of ClearingSite is serialized; the value of the base class' effectiveDatespan member is not serialized.

Two notes:

  1. I can see that the BaseType member of the added ProtoBuf.Meta.MetaType is set to null, causing the effectiveDatespan member to not be serialized; if I compile the model, instead, its BaseType member is correctly set to DimensionEntity (though it fails later on as the members are private readonly and thus not accessible by a compiled model);
  2. Of course I can declare ClearingSite as a known type of DimensionEntity, but I can't see why this would be required: I am not serializing a DimensionEntity, I'm serializing (and de-serializing) a ClearingSite, and furthermore the DataContractSerializer does not require me to add KnownType to DimensionEntity if I'm serializing a ClearingSite.

From other answers from Marc, it looks like Protobuf would require the KnownType (or ProtoInclude) attribute in order to get the "all-important field-number" (quote), but that seems to not be the case, as the CompiledModel works totally fine without ProtoInclude.

Note that I'm striving to use System.Runtime.Serialization attributes only, as I'm trying to keep my object model unaware of serializers down the road.

Upvotes: 3

Views: 1076

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062780

ProtoInclude, or an equivalent, is definitely required. If something is happening oddly with the compiled version, then that is a bug and I can investigate.

If you don't want to add non-BCL attributes to your type, this can be done at runtime:

RuntimeTypeModel.Default[typeof(BaseType)]
    .AddSubClass(.....);

(or somethig like that - I'm not at a PC)

Upvotes: 2

Related Questions