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.
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.