0

I'm building web API. I have a problem where input differs from the output, for example, input expects just the id and output returns entire object.

Also, there are few things specific to the output that should never be sent in the input. For example, something that server calculates and returns it, but the client doesn't need to pass this value.

I'm currently using DTOs, they're the same for both input and output.

Minimal example:

public class ProductDto
{
    // Should be only included in the output, should be ignored on the input
    public decimal SomePropertyCalculatedOnTheServer { get; set; }

    // Should only be included in the output
    public TaxDto Tax { get; set; }

    // Only for input
    public int TaxId { get; set; }
}

I can probably just ignore those things in my mapping configuration but wouldn't it be better to create a separate model for input and output? Currently it looks nasty and it's hard to maintain.

My service layer accepts those Dtos, maps them to my entities and operates on them, then maps them back and returns them. Everything uses 1 model.

Task<TEntityDto> CreateAsync(TEntityDto entityDto)

  • I'm not seeing sufficient requirements/design elaboration for a "do it" decision. From reading Martin Fowler the default is "why" vis-a-vis "why not". I've had satisfying success with a factory analyzing the data and injecting it into the appropriate class (constructor). Perhaps because these 7 different "record types" were all going to the same DB table I never considered using CQRS. In fact the data was similar enough that I used one class and injecting different IEquatable implementations. – radarbob Jun 12 '18 at 16:01
  • 1
    I have never implemented CQRS. That said I think that there is not enough information in your description to really decide. If you are just weary about the extra fields that have default values when updating, maybe you could have an inherited model which you return, and that contains the extra fields, whereas the base model only contains the fields that you would expect to be posted? Sidenote: there have been much talk about graphql graphql.org/learn which allows you to specify which fields to get or to update. – mortb Jun 14 '18 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.