Can I apply ModelState to an entity mapped from a DTO passed to the controller, and if not how would you apply fluent APIs to a DTO without generating a table?
To add more context to this question... I have added some fluent API validations to my entities, for example Author has an associated AuthorConfiguration class:
public class AuthorConfiguration : EntityTypeConfiguration<Author>
{
public AuthorConfiguration()
{
HasKey(b => b.Id);
Property(c => c.Name)
.IsRequired()
.HasMaxLength(2000);
}
}
which in the AppContext class is set:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new AuthorConfiguration());
}
In the controller, I have this, however:
// POST: api/authors
public IHttpActionResult Post([FromBody] AuthorCreateDto author)
{
var authorToInsert = Mapper.Map<Author>(author);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_unitOfWork.Authors.Add(authorToInsert);
_unitOfWork.Complete();
return StatusCode(HttpStatusCode.Created);
}
And the problem is that I am able to insert an author that has no name! I think this is because in the controller ModelState.IsValid would always return true as AuthorCreateDto does not have any validations. So, my questions are:
- how can I apply ModelState.IsValid to the authorToInsert after being mapped from Dto?
- Secondly, if that is not possible, and it turns I should duplicate the validations on the DTOs, similarly to the validations that I have on the domain models, another problem. I opted to have fluent API validations on domain models. If I create a configuration class similarly for the DTOs, I should inherit from : EntityTypeConfiguration and the result of this would be a new table being created in the database. So, does this mean that on DTO I cannot have fluent API validations, just data annotations?
PS. I did make it work with a Required data annotation on the DTO, but I feel this is not recommendable if the domain model has fluent API validation. It's not consistent from an overall design standpoint. Thank you.