创建DTO,有点困惑

时间:2012-02-26 12:47:22

标签: c# dto

刚刚注册。第一个问题:) 如果我在我的域模型实体Country中有Name属性和List of States属性。此外,国家有名称,州名单属性,进一步,广州有市镇,最后是城市实体。

更好地说:我正在尝试使用CountryDTO来保护国家实体,我的构造函数如下:

    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);
        }        
    }

但是当我对StateDTO更深入时,看起来像这样&gt;

    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);
        }
    }

由于我的StateDTO应该知道他的国家父对象我有这条线  CountryDTO Country = new CountryDTO(x.Country);这是问题,(可能是递归引用),这将发生在Cantons中,其State对象为parent,等等。 所以如何加载这个父实体并避免这个错误。 我需要引用父对象,如Country.Name no CountryName作为字符串。

希望,我很清楚:)。

2 个答案:

答案 0 :(得分:0)

您可以将public void StateDTO(State x)更改为public void StateDTO(State x, CountryDTO parent),然后使用StateDTO stateDto = new StateDTO(state, this);进行调用。

this运算符与CountryDTO实例相反,您可以将其传递给子代。

答案 1 :(得分:0)

我认为你的问题是尝试过多地反映你拥有域模型的东西。你最好考虑一下你在客户端真正需要什么,然后让dto反映出来,而不是重复你在域中所拥有的东西。这一点尤其如此,因为每次为服务调用服务时,您都会为一个国家/地区的所有内容序列化整个层次结构。在几乎所有情况下回送似乎都太过分了。这篇文章更好地描述了这一点:

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