I have Dto class with data annotations on my properties, but one of them is getting ignored when ModelValidation is performed:
Dto Class:
public class TestClassDto {
[Required()] //This one is getting ignored!
public virtual System.Guid Id { get; set; }
[StringLength(32)]
[Required()]
public virtual string Type { get; set; }
[Required()]
public virtual string Description { get; set; }
}
Original Class:
public class TestClass {
public virtual System.Guid Id { get; set; }
public virtual string Type { get; set; }
public virtual string Description { get; set; }
}
My Post Controller:
[HttpPost]
public async Task<IActionResult> PostTestClass([FromBody] TestClassDto testClassDto) {
//if (!ModelState.IsValid) return BadRequest(ModelState); Explicit ModelState Validation is not necessary because ControllerBase makes Validation automatically
TestClass testClass = _mapper.Map<TestClassDto, TestClass>(testClassDto);
_uow.TestClassRepository.Add(testClass);
try {
await _uow.CompleteAsync();
} catch (DbUpdateException ex) {
return StatusCode(500, ex.ToString());
}
TestClassDto result = _mapper.Map<TestClass, TestClassDto>(testClass);
return CreatedAtAction("GetTestClass", new { id = result.Id }, "Great");
}
Why is this happening? Any ideas would be helpful! Thanks in advance :)
System.Guid
is a value type and it has a default value (actually an instance of) Guid.Empty
, so it's never null. Because of that, the [Required]
attribute will always pass the validation.
One of the solutions and probably the easiest one is to make the Guid nullable, like so:
[Required]
public virtual System.Guid? Id { get; set; }
or the longer version:
[Required]
public virtual Nullable<System.Guid> Id { get; set; }