What is the correct way to use DTO in this case?

I have the following domain class:

public class Product
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual IList<Product> RelatedProducts { get; set; }
}

I have the following DTO class:

public class ProductDTO
{
    public ProductDTO(Product product)
    {
        Id = product.Id;
        Name = product.Name;
    }

    public Guid Id { get; private set; }
    public string Name { get; private set; }
}

I have the following method in my service:

public ProductDTO GetBySlug(string slug)
{
    Product product = productRepository.GetBySlug(slug);
    return (product != null) ? new ProductDTO(product) : null;
}

My controller has the following action:

public ActionResult Details(string slug)
{
    ProductDTO viewModel = productService.GetBySlug(slug);
    return View("Details", viewModel);
}

After reading a little, I understand that using DTO as a view model is normal, as the current scenario is simple and simple. My confusion arises when the data I want to return becomes a little more complicated. Suppose I also want to return a list of related products to the view. Where can I add this list?

, DTO - , . , , , DTO? , , . ?

:

, ProductDTO , , ProductDTO List ProductDTO . , ProductViewModel, ProductDTO List ProductDTO , .

? ?

+3
1

DTO , , , . , -. , , , , .

, - :

public IList<ProductDTO> GetRelatedProducts(ProductDTO productDTO)
{
    ...

viewmodel (, ) , -. : - , . - , . , , , - .

!

P.S. DTO , , () DTO , , .

+2
source

Source: https://habr.com/ru/post/1758574/


All Articles