Search code examples
.netreflectioncode-generationdtocodedom

Auto-implement persistence/clone functionality in DTO classes


I need to create DTO objects which holds simple properties and needs to implement the following functionality:

  • Load From XML node
  • Save to XML node
  • Clone

Programming these function is each DTO over and over again would be very tedious and error prone I think so I though about alternatives.

  1. Use Reflection, would be very slow I guess
  2. C# Code generation as pre- or postbuild step (both would require building the solution twice, since I need a compiled class to get info which code to generate)
  3. Use CodeDom? I think this is the most complicated solution

What is the best/simplest common way to accomplish such a task? How Can I determine which one to chose or are there alternatives?


Solution

  • You could load and save from XML using System.Xml.Serialization.XmlSerializer and the Deserialize and Serialize methods.

    Cloning can be performed by AutoMapper.