How to create a DTO in asp.net?

1) I want to know what is the recommended way to create and return a DTO for an object that has 10 attributes, and I only want to return 2 with my DTO object.

2) Should a DTO have its own namespace? If so, how do we organize them? Each DTO inside a single class file or the entire DTO inside a single class?

Please provide me an example code.

+4
source share
2 answers

DTOs are dumb objects consisting of public getters / setters. I usually put them in a separate namespace called SomeProject.Dto.

public class CustomerDto { public int Id { get; set; } public string Name { get; set; } public LocationDto HomeAddress { get; set; } } 

Usually I try to keep property names the same between the DTO and the corresponding domain class, possibly with some smoothing. For example, my Client may have an Address object, but my DTO may have a smooth value:

 public class CustomerDto { public int Id { get; set; } public string Name { get; set; } public string HomeStreet { get; set; } public string HomeCity { get; set; } public string HomeProvince { get; set; } public string HomeCountry { get; set; } public string HomePostalCode { get; set; } } 

You can significantly reduce the number of duplicate display codes for translating domain objects in the DTO using Jimmy Bogard AutoMapper.

http://automapper.codeplex.com/

+10
source

Your question is very open. The answers depend on the scale of your application.

In general, I create my DTO or ViewModels in my own assembly. To get my DTO, I have some level of service that takes care of creating them based on my request.

If you want specific examples, consider some of the Asp.NET ASPC examples on asp.net. Although you cannot use MVC, you can at least see how ViewModels are created.

+1
source

All Articles