Why doesn't my <Foo> list serialize with protobuf-net?

[DataContract] public class Foo 
{
   [DataMember(Order = 1)] public int FooId { get; set; }
}

[DataContract] public class Bar : Foo 
{
   [DataMember(Order = 2)] public string Name { get; set; }
}

[DataContract] public class Baz : Bar
{
    [DataMember(Order = 3)] public string BazName { get; set; }
}

Then in the code I install a new TypeModel and add my subtypes

_ProtobufSerializer = TypeModel.Create();
_ProtobufSerializer.Add(typeof(Bar), true);
_ProtobufSerializer.Add(typeof(Baz), true);
var type = _ProtobufSerializer.Add(typeof(Foo), true);
type.AddSubType(100, typeof(Bar));
type.AddSubType(101, typeof(Baz));

Now I can arrange the instances of Foo, Bar and Baz in order. If I serialize

var listThatWorks = new List<Foo> { new Foo { FooId = 12 } }
var anotherListThatWorks = new List<Foo> { new Bar { FooId = 12, Name = "Test" } }

It works great. However, if I serialize

var fails = new List<Foo> { new Baz { FooId = 12, Name = "Test" } }

Then I get an InvalidOperationException with the message "Unexpected subtype: Baz". What am I doing wrong? Is it just a bad idea to use subtypes with protobuf-net?

Also, thanks to @BFree in order to help me figure it out, this is due to the presence of two levels of subclasses.

+5
source share
1 answer

. , BFree. , , . , Baz Bar, Foo. TypeModel, . :

_ProtobufSerializer = TypeModel.Create();
_ProtobufSerializer.Add(typeof(Baz), true);
var barType = _ProtobufSerializer.Add(typeof(Bar), true);
var fooType = _ProtobufSerializer.Add(typeof(Foo), true);
fooType.AddSubType(100, typeof(Bar));
barType .AddSubType(101, typeof(Baz));

, .

+4

All Articles