سؤال

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).

  • Should CategoryDTO have a collection of type ProductDTO or a collection of type Product?
  • Should ProductDTO have a CategoryDTO as navigation property or a Category or just an Id to the Category?

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.

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top