We are using DTOs as Data Contracts in our WCF web service. The purpose for these DTOs is to expose only the information that is relevant for a specific API method.
What I am seeking from you guys is some advise on the best practices here.
For example, consider the following simple model:
class Order
{
int CreatedBy { get; set; }
DateTime CreatedOn { get; set; }
string Description { get; set; }
int Id { get; set; }
string Name { get; set; }
}
Assuming our API allows a consumer to Create, Update and Get an Order, we have created the following DTOs. DataMember and DataContract attributes are eliminated for simplicity.
Create method: A user cannot specify the Id and CreatedOn properties, so the DTO looks like this:
class CreateOrderData
{
int CreatedBy { get; set; }
string Description { get; set; }
string Name { get; set; }
}
Update method: A user cannot specify the Id, CreatedOn and CreatedBy properties, so the DTO looks like this:
class UpdateOrderData
{
string Description { get; set; }
string Name { get; set; }
}
Get method: A user should be able to see everything for the Order, so the DTO looks like this:
class OrderData
{
int CreatedBy { get; set; }
DateTime CreatedOn { get; set; }
string Description { get; set; }
int Id { get; set; }
string Name { get; set; }
}
So here are my questions:
Assuming there are more properties in Order model and lot of those properties are shared between "Create" and "Update" DTOs, does it make sense to have these classes extend from a common base class? If yes, should the "Get" DTO (OrderData) also extend from that class? If we do that, doesn't it leave these DTOs too dependent on each other?
If all the properties are common between "Create" and "Update" DTOs, should we still create two different DTOs? If yes, why? If not, (this is just a naming question now) what should the "CreateOrUpdate" DTO be called so that the name is obviously different from the "Get" DTO?
Is it OK to suffix all the DTOs with something like "Data" or "DataObject" or "Dto"?
Are we on the right track here? If not, how can be make this design better?
Update:
I think I don't like the inheritance in DTOs because the base class will also be exposed in the WSDL and the client will be able to see it and instantiate it which seems dirty to me (see this: WCF Serialization with object inheritance?). How about using Interfaces in DTOs to enforce common properties instead of inheritance? Since DTOs should not have any behavior in them, we are not losing much by replacing inheritance.
Upsert
. I'd leave out any suffix like the hungariandto
notation as you can easily identify the type and IMHO its better to use namespace likeProject.Data.DataObjects
rather than suffix's. Just my 2 cents – Boothe