0

In my C# .NET project, I use object serialization and TCP/IP to pass information from a server to a client and vice versa. The software package manages contact information and has a static data class, containing a list of all Person objects and a list of all Address objects. Persons and addresses are related 1:N, so a person references a list of its addresses.

The communication involves the server supplying the client with all Persons.

Now when the client receives the Persons array, there is an instance made of each address, even if multiple persons live at the same address. If I understood it right, serialization has to break the references and include each address in a Person everytime it is referenced.

My question is how I can have the client understand identical addresses, populate its own static collection of all Addresses, and reference them from then on.

Note that both persons and addresses hold an Id and can be distinguished.

My thoughts on solving this were:

  • Excluding the Addresses property in a Person object from serialization and instead sending a list of integers containing the Id's of all its addresses. It does not seem very smart to me, because I'd clog the Person class with all kinds of fields that are only needed for the transmission process.
  • Making the Addresses relation in a Person object lazy-evaluate to go through the complete static list and collect the needed addresses upon calling the field. However the server initializes the data through an SQL join, which already returns the person alongside their addresses.

Thanks in advance for your help.

Fabi
  • 199
  • 1
  • 14
  • 1
    There's no standard way to preserve references when serializing. Some serializers support it, others don't. For [tag:DataContractSerializer] see [IsReference property in data contract](https://stackoverflow.com/q/1037201/3744182). For [tag:json.net] see [What is the difference between PreserveReferencesHandling and ReferenceLoopHandling in Json.Net?](https://stackoverflow.com/q/23453977/3744182). For [tag:protobuf-net] see [protobuf-net serializing object graph](https://stackoverflow.com/q/6294295/3744182). – dbc Jun 04 '20 at 14:45
  • 1
    Or you could handle it at a higher level by using DTOs or surrogate properties that refer to each other by IDs, then resolve the references after deserialization completes. – dbc Jun 04 '20 at 14:46
  • what is the format used? xml or json? – IamP Jun 04 '20 at 16:07
  • @IamP it actually is binary serialization. – Fabi Jun 05 '20 at 06:37

0 Answers0