Search code examples
c#dto

Creating DTO, bit confused


just registered. First question :) If I have in my domain model entity Country which have Name property and List of States property. Further that State have Name, List of Cantons property, further, Canton have municipalities, on the very end is city entity.

To exaplain better: I'm trying to seriliaze Country entity with CountryDTO and my contructor looks like this:

    public CountryDTO(Country x)
    {
        Name = x.Name;
        StateList = new List<StateDTO>();
        foreach (State state in x.States)
        {
            StateDTO stateDto = new StateDTO(state);
            StateList.Add(stateDto);
        }        
    }

But when I'm going deeper with StateDTO which looks like this>

    public StateDTO(State x)
    {
        Name = x.Name;
        CountryDTO Country = new CountryDTO(x.Country);

        CantonList = new List<CantonDTO>();
        foreach (Canton c in x.Cantons)
        {
            CantonDTO cantonDto = new CantonDTO(c);               
            CantonList.Add(cantonDto);
        }
    }

Since my StateDTO should be aware of his Country parent object I'm having this line CountryDTO Country = new CountryDTO(x.Country); which is the problem, (possibly recursive reference), this will happen in Cantons with their State object as parent, and etc. So how to load this parent entity and to avoid this error. I need reference to parent object like Country.Name no CountryName as a string.

Hope, I was clear enough :)


Solution

  • i think your problem is trying too much to mirror in the dto what you have the domain model. you would be better off considering what you really need on the client side and make the dto reflect that rather than being a duplication of what you have in the domain. this is especially true in that every time you are servicing a call to your service, you are serializing the entire hierarchy for everything in a country. seems like way too much to send back in almost all cases. here is a good post that describes this better:

    http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/