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;
}
I have the following action in my controller:
public ActionResult Details(string slug)
{
ProductDTO viewModel = productService.GetBySlug(slug);
return View("Details", viewModel);
}
After reading around a bit is my understanding that using a DTO as a viewmodel is ok as the current scenario is simple and straight forward. My confusion occurs when the data that I want to return gets a bit more complex. Let's assume that I also want to return the list of related products to the view as well. Where would I add this list?
I read that a DTO is a flattened version of your domain entity that is used to transfer data. Does that mean that a generic list containing the related products should not be allowed inside the DTO? The answer I received so far suggests so. How do I then get the related products to the controller?
One option is:
Instead of returning the ProductDTO in the service I would create a new class that holds ProductDTO and the List of type ProductDTO for the related products and return it from the service. In the controller I would then either pass the new class to the view or create a separate ProductViewModel that holds ProductDTO and the List of type ProductDTO for the related products, populate it and pass that to the view.
Is this a good or a bad idea? Why?
Thanks