Search code examples
c#asp.netasp.net-mvcrestdto

Using DataAnnotations in the entitie is necessary when already using in Dto members?


For example, if I'm not requesting for a Item, but a CreateItemDto, that does not have only the Id propertie, should I use DataAnnotations like [Required] in the Title propertie of the Item class? Cause it will be passed in CreatedItemDto, that uses [Required] data annotaiton.

Item Record:

public record Item
{
    public Guid Id { get; init; }
    public string? Title { get; init; }
}

CreateItemDto Record:

public record CreateItemDto
{
    public Guid Id { get; init; }
    
    [Required]
    [Range(1, 20)]
    public string? Title { get; init; }
}

In my controller, something like that would take it:

[HttpPost]
ActionResult<ItemDto> Create(CreateItemDto item)
{
    var newItem = new Item() { Guid = Guid.NewGuid(), Title = item.Title };
    return CreatedAtAction(nameof(Get), new { id = newItem.Id }, newItem );
}

Solution

  • Depends on the approach you are using with this.

    If you have a single endpoint to manipulate the object, I think that the DTO validation is enough to achieve your goal. But if the project grows, contexts are not well defined or you are working with other people on a team, the domain object can be instantiated elsewhere in the application. On my current team, what works for us is doing the domain object validation in the domain service before the business rules.

    In my opinion, this approach will depend on each team's scenario, so it's worth doing some testing to understand what meets your need and find a pattern that works for everyone.