I'm currently creating a .NET C# API. I have many classes, and some of them have to be transferred through a REST
service as JSON
. For example, I may have an account object with a lot of business meta-data:
public class Account
{
public ComplicatedClass SomeProperty { get; set; }
public string SomeOtherProperty { get; set; }
}
There are many classes, and many more that are nested (as demonstrated by ComplicatedClass
type property). To avoid inundating this business-object with [DataMember]
etc. Attributes that will make this class a mess, I want to make a DTO
for JSON
:
public class AccountDTOForJSON
{
[DataMember(Name="someProperty")]
public ComplicatedClassDTOForJson SomeProperty { get; set; }
[DataMember(Name="someOtherProperty")]
public string SomeOtherProperty { get; set; }
}
My problem is, there doesn't seem to be any tools (that I can find) to auto-generate these DataContract
classes, and also provide code for mapping properties back/forth.
I can, of course, do all this work manually (worst case), or roll my own tool to generate/map (second worse case). But, I'd like to know first if there's already a tool to do this kind of thing that I can use to save myself time.
This is a good question. I'm actually going to be doing something similar to it in a project I am working on.
I would suggest that there are really two problems here: the first is to generate DTO code from your business objects, and the second is to do the mapping between business object and DTO.
I could not find a code generator for this purpose after spending about a half hour on Google. Perhaps I'm not searching for the right thing, or possibly there isn't one out there (so if someone knows of one, please chime in). The only tool I found that looks promising is NHydrate (http://www.codeproject.com/Articles/42885/NHydrate-Code-Generator), but I did not actually download it or test it.
A mapping tool that I've used in the past is AutoMapper (https://github.com/AutoMapper/AutoMapper/wiki/Getting-started) - it will attempt to figure out the relationship between your business objects and DTOs, and will be able to do two-way mapping.