How is Modelstate.IsValid triggered?

Hello!

I am reading this tutorial on how DTO's can be implemented with API's: https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e

The process in this tutorial seems normal and you can easily follow along.

There are only 2 things I have my questions about:

  1. The Driver class in this tutorial has no DataAnnotations (see first codeblock). How come the Modelstate.IsValid can be triggered in codeblock 2?
    ```cs
    namespace SampleMapper.Models;
public class Driver
{
public Guid Id { get; set; }
public string FirstName { get; set; } = "";
public string LastName { get; set; } = "";
public int DriverNumber { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateUpdated { get; set; }
public int Status { get; set; }
public int WorldChampionships { get; set; }
}
2. How does Modelstate.IsValid get triggered when a Dto is passed but it gets mapped to an entity?
cs
[HttpPost]
public IActionResult CreateDriver(DriverCreationDto data)
{
var _driver = _mapper.Map<Driver>(data);

if(ModelState.IsValid)
{
drivers.Add(_driver);

return CreatedAtAction("GetDriver", new {_driver.Id}, data);
}

return new JsonResult("Something went wrong") {StatusCode = 500};
}
```
DEV Community
Intro In this article we will be exploring AutoMapper and Data Transfer Objects (DTOs) in...
Was this page helpful?