Frage

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?

War es hilfreich?

Lösung

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.

Andere Tipps

I would suggest a Component Layer. It should be responsibly for communication between your business layer and your data layer. In this case, you can use it to translate your DTO objects to Business Objects.

You're concern "no need to expose business object guts to DTO" seems bit unfounded unless there is something you are not showing in you code since you are accessing public properties, i.e. not the guts at all.

As an aside, instead of having clone methods you could implement a cast operator instead: MSDN

That way you can do something like: Person p = (Person)myPersonDTO;

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top