How should my DTO be for ASP.Net MVC View?

I would like to know I have an application in asp.net mvc and nhibernate. I read about this in asp.net mvc views, don't need to know about Domain, and needs a DTO object. So I am trying to do this, I found the AutoMapper component and I don’t know how to use DTOS correctly for some domain objects. I have a domain class like this:

public class Entity 
{
   public virtual int Id { get; set; }
   public virtual bool Active { get; set; }
}

public class Category : Entity 
{ 
   public virtual string Name { get; set; }
   public virtual IList<Product> Products { get; set; }

   public Category() { }
}

public class Product : Entity 
{ 
   public virtual string Name { get; set; }
   public virtual string Details { get; set; }
   public virtual decimal Prince { get; set; }
   public virtual int Stock { get; set; }
   public virtual Category Category { get; set; }
   public virtual Supplier Supplier { get; set; }

   public Product() { }
}

public class Supplier : Entity 
{
   public virtual string Name { get; set; }
   public virtual IList<Product> Products { get; set; } 

   public Supplier() { }  
}

      

I would like to give an example of how I can use my DTOs to view? Should I only use strings in DTOs? And my controllers, is it supposed to get a domain object or DTO and convert it to a domain to be stored in the repository?

Thank you very much!

Greetings

+2


a source to share


1 answer


There are no guidelines on this and it depends on your personal taste. I have few tips that have proven useful in practice:
1. Use flat DTOs - this means that DTO properties should be as primitive as possible. This saves you the trouble of checking for a null reference. For example, if you have a domain object like:

public class Employee
{
  prop string FirstName{get; set;}
  prop string LastName{get; set;}
  prop Employee Boss{get; set;}
  ...
}

      

And you need to display the list of employees in the grid and display information for your 1st level boss. I prefer to create DTOs



public class EmployeeDTO
{
  prop string FirstName{get; set;}
  prop string LastName{get; set;}
  prop bool HaveABoss{get;set}
  prop string BossFirstName{get; set;}
  prop string BossLastName{get; set;}
  ...
}

      

or something like this (- :: 2. Don't convert everything to sting - this will bind the DTO to a specific view, because you will apply special formatting. It's not a problem of applying simple formatting directly in the view.
3. Use DTOs in your post actions and then convert them to domain objects. Typically controller actions are the first line of defense against bad data and you cannot expect to be able to completely create a valid domain object outside of user input. In most cases you need to do some post-processing. eg validation, setting defaults, etc. After that, you can create your DTOs.

+1


a source







All Articles