【问题标题】:How to design DTO classes for nested domain objects?如何为嵌套域对象设计 DTO 类?
【发布时间】:2014-03-14 14:24:33
【问题描述】:

我是使用 DTO 的新手。

我有两个域类:

  1. 类别
  2. 产品

如下

public class Category
{
    // Properties
    public int Id { get; set; }
    public string Name { get; set; }

    // Navigation properties
    public virtual Category ParentCategory { get; set; }

    // Foreign key
    public int? ParentCategoryId { get; set; }

    // Collections
    public virtual ICollection<Product> Products { get; set; }
    public virtual ICollection<Category> Subcategories { get; set; }
}

public class Product
{
    // Properties
    public int Id { get; set; }
    public string Name { get; set; }

    // Navigation property
    public virtual Category Category { get; set; }

    // Foreign key
    public int CategoryId { get; set; }
}

我想使用 Automapper。

我不确定如何为上述聚合(图表)设计 DTO。

  • CategoryDTO 应该有一个 ProductDTO 类型的集合还是一个 Product 类型的集合?
  • 应该ProductDTO 有一个CategoryDTO 作为导航属性或一个Category 或只是一个ID 到Category

谁能推荐 DTO 的代码? 这个结构应该如何展平(如果应该)并映射到域类?

提前非常感谢。

【问题讨论】:

  • 您创建 DTO 是有目的的。目的定义了 DTO 的内容。因此,只有在我们知道您需要 DTO 的用途时才能回答这个问题。
  • 我想通过使用 DTO 作为 ViewModel 将 MVC Web 应用程序的表示层与域类分离。
  • 这里的 DTO 将用于将对象传递到业务层,然后从那里传递到数据层,以便对网站管理面板中的类别和产品进行 CRUD 操作。

标签: automapper dto


【解决方案1】:

我将我的 DTO 设计为仅用于 MVC 的特定控制器操作的数据。通常这意味着如果我有一个 CategoryController,那么我就有一个 CategoryIndexModel、CategoryDe​​tailsModel、CategoryEditModel 等。仅在该屏幕上包含您想要的信息。我尽可能地扁平化,除非我有 Partial 或集合,否则我不会创建子 DTO。

【讨论】:

  • 所以我的代码示例中的集合应该是ICollection&lt;ProductDTO&gt;,对吧?
猜你喜欢
  • 1970-01-01
  • 2014-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-19
  • 2016-04-29
  • 2017-04-05
  • 1970-01-01
相关资源
最近更新 更多