mko
mko

Reputation: 7325

Need for using different DTOs on web api resource

I have couple of DTOs that I am using in WEB API and I have noticed that I am reusing same properties over and over again.

For example

public class Response
{
public int Id {get;set;}
public DateTime CreatedOn {get;set;}
public string Name  {get;set;}
public string Code {get;set;}
}
public class InsertRequest
{
public string Name  {get;set;}
public string Code {get;set;}
}

Is there really a need to specify InsertRequest for a resource, since DTOs are processed later in the code? It could be misleading to have property Id available in code even if Id would not be inserted.

On the other hand if Id is declared as nullable, it can be misleading since Id in Response should not be nullable, so I am in doubt should these two request be split or should they all be in one representing a resource?

Upvotes: 0

Views: 199

Answers (1)

Andrei Dragotoniu
Andrei Dragotoniu

Reputation: 6335

The situation you describe is pretty common for situations where you have to create / update entities.

I would recommend you keep yours as they are. CreatedOn makes no sense when you want to update and Id, well, it'll never change once created, so again, it makes no sense to have it in a change entity. Plus, chances are that you will provide your Id in the route so the actual entity doesn't need it anyway:

PUT against:

www.somedomain.com/entity/id

entity doesn't need id field as its coming from the URI.

Yes, you can argue that you will end up with entities with duplicate fields, but at the same time you'll have a clean API which makes sense and that's more important as this is what the clients will be seeing and using.

One more thing, I am in favor of keeping a clear naming convention so if one entity is InsertRequest then the other will be UpdateRequest.

Upvotes: 2

Related Questions