Business Logic in Data Transfer Objects (DTOs)
While Data Transfer Objects (DTOs) are meant to be simple data containers with no functionality, there may be cases where you would like to add some simple business logic or data formatting within your classes that doesn’t require a call across the network using a service method.
For instance, let’s say we have a User DTO class that contains a property with the person’s height in inches. If we would like to add some code to compute the person’s height in feet and inches (e.g., 5 feet, 11 inches), it would be nice to add this within the DTO class itself.
Since the generated proxy code uses partial classes, we have a fairly simple solution. Within our client application, we can add on to the class using the “partial” keyword and then include any additional logic that we need to perform. Be sure not to make this too complicated since any complex business logic should be done within the business layer, but this is an easy way to implement data formatting or simple computations.
namespace Example.Business.DataTransferObjects
{
public partial class UserDto
{
public int HeightFeet
{
get
{
return this.CurrentHeight / 12;
}
}
public int HeightInches
{
get
{
return this.CurrentHeight % 12;
}
}
}
}
