I have a WCF service and have just created a DTO for a business object.
My question is where to put the mapping between the two?
A) In the DTO?
public class PersonDTO
{
[DataMember] public string Id { get; set; }
[DataMember] public string Name { get; set; }
public void CloneFrom(Person p)
{
Id = p.Id;
Name = p.Name;
}
public void Populate(Person p)
{
p.Id = Id;
p.Name = Name;
}
}
or
B) In the business object?
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
public void CloneFrom(PersonDTO dto)
{
Id = dto.Id;
Name = dto.Name;
}
public PersonDTO GetDTO()
{
return new PersonDTO()
{
Id = Id;
Name = Name;
}
}
}
I like the separation of concerns in A (Business object has no knowledge of DTOs), but I prefer the encapsulation of B (no need to expose business object guts to DTO).
Just wondered if there was a standard way?
i'd think this calls for a separate class, as neither the BO nor the DTO should be concerned with their transformation into another class.
I personally use the automapper library for object transformations. With simple transformations like in your example the mapping is done in a single line of code, complex transformations are also easy to set up.
If you want to map yourself, you could still use extension methods to keep the mapping implementation separated from your DTO and BO classes.