Kamran
Kamran

Reputation: 780

How to design DTO classes for nested domain objects?

I am new to using DTOs.

I have two domain classes:

  1. Category
  2. Product

as follows

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

I want to use Automapper.

I am not sure how to design DTOs for the above aggregate (graph).

Can anyone suggest the code for DTOs? How should this structure be flattened (if it should) and mapped to domain classes?

Many thanks in advance.

Upvotes: 3

Views: 2799

Answers (1)

Jimmy Bogard
Jimmy Bogard

Reputation: 26765

I design my DTOs to be only the data used for a specific controller action for MVC. Typically this means if I have a CategoryController, then I have a CategoryIndexModel, CategoryDetailsModel, CategoryEditModel etc etc. Only include the information you want on that screen. I flatten as much as I can, I don't create child DTOs unless I have a Partial or collection.

Upvotes: 2

Related Questions