C#: Library for mapping one complex object to another
I'm getting a complex object from the server - lets call it ServerDTO. I want to map it to a client side object - lets call it ClientDTO.
assuming both ServerDTO & ClientDTO have the same structure inside them.
I want to map the ServerDTO object to the ClientDTO object. very simple mapping like so:
ServerDTO sd = server.Result;
ClientDTO cd = new ClientDTO();
cd.Property1 = sd.Property1;
cd.JahRas = sd. JahRas;
and so on...
so far so good.
now my question is can this mapping be done in some abstracted layer that can handle all the mapp开发者_运维问答ing of all my objects no matter what type or what's inside them?
so when I want to map I'll go:
ClientDTO cd = Mapper.Map(sourceServerDTO, typeOf(ClientDTO));
You might want to look at Automapper
As Steve said, I'd try to use only one type. To avoid referencing directly the web service, migrate all the interfaces / common types into a common assembly that both your client and server will reference. Obviously, this assumes that you have hands on both codebases.
If the 2 objects have the same structure and you want to mirror the content why do you even need 2 different types? Can you not just use ServerDTO type in your client code too?
I know there are times when you need separate types, but I'd think twice before doing this.
If you do need different types then I think Automapper (link posted by Lee in separate answer) is a good bet.
Shared types between client and server only works if you are not going to have different applications calling the same server. (This sort of defeats the one of the main benifits of having a set of servers) If you do share types you end up with one big splurge of a domain model where changes in one application breaks things in another. i.e asmall change on one client that doesn't even involve a change to the service interface can lead to a rollout of your whole application suite..
I would never say never but shared types is rarely a good idea.
精彩评论