Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a DTO in asp.net?

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

2) Should DTO's have their own namespace ? If yes, how do we organize them ? Each DTO inside a single class file or all DTO's inside a single class ?

Please provide me some sample code.

like image 201
Zo Has Avatar asked Dec 02 '10 04:12

Zo Has


2 Answers

DTOs are dumb objects composed of public getters/setters. I generally 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; }
}

I generally try to keep the property names the same between the DTO and corresponding domain class, possibly with some flattening. For example, my Customer might have an Address object, but my DTO might have that flattened to:

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 dramatically reduce the amount of repetitive mapping code of translating domain objects into DTOs by using Jimmy Bogard's AutoMapper.

http://automapper.codeplex.com/

like image 103
James Kovacs Avatar answered Oct 22 '22 06:10

James Kovacs


Your question is very open ended. The answers are dependent on the scale of your application.

In general I create my DTO's or ViewModels in their own assembly. To get my DTO's I have some service layer take care of creating them based on my request.

If you want concrete examples take a look at some of the Asp.NET MVC examples at asp.net. While you may not be using MVC you can at least see how the ViewModels are created.

like image 24
Brownman98 Avatar answered Oct 22 '22 05:10

Brownman98