A DTO (Data Transfer Object)
is an object that defines how the data will be sent over the network or application. On the other hand Response Object
which usually holds response data from DTO's or WebApi's or Data Access
or any other responses to client.
The Response Object
which usually includes all/few properties of a particular model or entity or DTO
which is usually a subset of DTO
object. Please see below example.
Employee Response Object:
public class EmployeeResponseObject
{
public int Id { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
}
Employee DTO:
public class EmployeeDTO
{
public int Id { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
public decimal Salary { get; set; }
public DateTime JoiningDate { get; set; }
public decimal Tax { get; set; }
}
Now you can see here. EmployeeResponseObject
is a subset of EmployeeDTO
which mean's EmployeeResponseObject
has fewer properties from EmployeeDTO
. In few scenario's we don't have to pass all information to end Client. So we will use EmployeeResponseObject
to get required properties from EmployeeDTO
.
You can use LINQ
to project data to Response Object
from DTO
.
[ResponseType(typeof(EmployeeResponseObject))]
public EmployeeResponseObject GetEmployee()
{
var employee = from e in dbContext.EmployeeDTO
select new EmployeeResponseObject()
{
Id = e.Id,
Name = e.Name,
Designation = e.Designation
};
return employee;
}
If you use only EmployeeDTO
to pass information to presentation layer/View, Webforms or ConsoleApp
then your presentation layer/View
will tightly coupled to your domain layer
. Any changes done to DTO Objects
requires you to change presentation layer or controllers
which is not a good way to do it.
Sometimes DTO
and Response Objects
will be exactly same then why to use separate objects.
This might look unnecessary duplication of code but think when your project grows bigger specially in a big teams where many people work together on different layers of application. Here using DTO
and separate Response object
makes much more sense with a good programming practice. Presentation layer/View
and the domain layer
will become tightly coupled when you skip using ResponseObject/ViewModelObject
.